5

html的dialog标签元素用法

 1 year ago
source link: https://blog.p2hp.com/archives/8963
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

以前的时候为了在页面上做出dialog效果往往很复杂,还要写遮罩层,用CSS 写 好多代码,不过刚刚知道html中原生也支持dialog。

<dialog open>
<h1>你好</h1>
</dialog>
<dialog open>
    <h1>你好</h1>
    </dialog>
在这里插入图片描述

可以通过改变open属性,来显示或者隐藏,如上图所示。也可以使用dialog的show方法或者close方法。

模态框(modal)用法

在这里插入图片描述

与普通用法不同的是,显示需要使用showModal方法,而模态框默认上下左右居中,还有默认的蒙层。当模态框显示的时候,可以按ESC键进行隐藏。

在这里插入图片描述

背景的样式可以通过::backdrop伪类进行修改,如上图把背景色修改成了蓝色;当然模态框的样式也可以同过CSS修改。

form形式的模态框

<dialog id="dialog">
<form method="dialog">
<p>要关闭?</p>
<button type="submit" value="no">否</button>
<button type="submit" value="yes">是</button>
</form>
</dialog>
<script>
const dialog = document.getElementById('dialog');
dialog.showModal();
dialog.addEventListener('close', function () {
console.log(dialog.returnValue); // yes or no
<dialog id="dialog">
    <form method="dialog">
        <p>要关闭?</p>
        <button type="submit" value="no">否</button>
        <button type="submit" value="yes">是</button>
    </form>
</dialog>

<script>
    const dialog = document.getElementById('dialog');
    dialog.showModal();
    dialog.addEventListener('close', function () {
        console.log(dialog.returnValue); // yes or no
    });

效果如下图:

在这里插入图片描述

其中,form的method属性要设置成dialog,里面两个button ,点击任何一个都会将dialog隐藏,close事件中的returnValue就是button的value,不限于no or yes;

参考文献:
https://www.viget.com/articles/the-dialog-element/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK