html H5 dialog弹窗学习,实现弹窗显示内容 替代confirm、alert
warning:
这篇文章距离上次修改已过280天,其中的内容可能已经有所变动。
HTML5 <dialog>
元素可以用来创建对话框,它可以作为弹窗来显示内容,并且可以通过JavaScript来控制显示和隐藏。以下是一个使用 <dialog>
元素的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Dialog Example</title>
<style>
dialog {
width: 300px;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 1px 1px 5px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<button id="alertButton">显示弹窗</button>
<dialog id="myDialog">
<p>这是一个使用HTML5 `<dialog>` 元素的弹窗。</p>
<button onclick="document.getElementById('myDialog').close();">关闭</button>
</dialog>
<script>
document.getElementById('alertButton').onclick = function() {
document.getElementById('myDialog').showModal();
};
</script>
</body>
</html>
在这个例子中,我们创建了一个按钮和一个 <dialog>
元素。当用户点击按钮时,通过JavaScript的 showModal()
方法显示弹窗。弹窗可以通过内部的按钮或者点击对话框以外的地方关闭。这种方式比 alert()
和 confirm()
更加现代和用户友好。
评论已关闭