js 实现dialog
使用HTML <dialog> 元素
HTML5原生提供了<dialog>标签,通过JavaScript的showModal()或show()方法控制显示。

<dialog id="myDialog">
<p>这是一个原生dialog</p>
<button onclick="document.getElementById('myDialog').close()">关闭</button>
</dialog>
<button onclick="document.getElementById('myDialog').showModal()">打开dialog</button>
showModal():以模态形式打开(阻止其他交互,默认带背景遮罩)。close():关闭对话框。
通过CSS和JavaScript模拟
若需兼容旧浏览器,可通过div+CSS模拟:

<div id="customDialog" class="dialog">
<div class="dialog-content">
<p>自定义dialog内容</p>
<button onclick="closeDialog()">关闭</button>
</div>
</div>
<button onclick="openDialog()">打开自定义dialog</button>
<style>
.dialog {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
align-items: center;
justify-content: center;
}
.dialog-content {
background: white;
padding: 20px;
border-radius: 8px;
}
</style>
<script>
function openDialog() {
document.getElementById('customDialog').style.display = 'flex';
}
function closeDialog() {
document.getElementById('customDialog').style.display = 'none';
}
</script>
使用第三方库(如SweetAlert2)
引入库后快速创建美观对话框:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<button onclick="showAlert()">触发SweetAlert</button>
<script>
function showAlert() {
Swal.fire({
title: '提示',
text: '这是一个第三方dialog示例',
icon: 'success',
confirmButtonText: '确定'
});
}
</script>
特点:支持图标、按钮定制、异步操作等。
注意事项
- 原生
<dialog>的浏览器兼容性需检查(IE不支持)。 - 自定义实现时注意
z-index和滚动条处理。 - 模态对话框应确保焦点管理(如
inert属性或手动控制)。






