HTML中dialog元素的使用

1. 直接贴代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dialog Demo</title>
    <style>
    dialog {
        background-color: lightcoral;
    }
    
    .dialog2 {
        width: 30vw;
        height: 20vw;
    }

    .dialog3 {
        width: 25vw;
        height: 15vw;
    }

    /* 自定义透明背景 */
    .dialog3::backdrop {
        background: rgba(45, 174, 197, 0.664);
    }
    </style>
</head>
<body>
    <button class="openBtn1" type="button">打开弹窗1</button>

    <dialog class="dialog1">
        <h3>我是弹窗1</h3>
        <input name="txt" placeholder="我会自动聚焦">
        <button class="openBtn2">打开弹窗2</button>
        <button class="closeBtn1">关闭</button>
    </dialog>

    <dialog class="dialog2">
        <!-- form可以自动关闭弹窗,需要 method=dialog -->
        <form method="dialog">
            <h3>我是弹窗2</h3>
            <input name="txt" placeholder="我会自动聚焦">
            <button class="openBtn3">打开弹窗3</button>
            <button>关闭</button>
          </form>
    </dialog>

    <dialog class="dialog3">
        <h3>我是弹窗3</h3>
        <p>我是水平垂直居中的,有本透明背景,且处于top-layer</p>
        <input name="txt" placeholder="我会自动聚焦">
        <button class="closeBtn3">关闭</button>
    </dialog>

    <script>
        document.querySelector(".openBtn1").onclick = openDialog(document.querySelector(".dialog1"));
        document.querySelector(".openBtn2").onclick = openDialog(document.querySelector(".dialog2"));
        document.querySelector(".openBtn3").onclick = openDialogModal(document.querySelector(".dialog3"));
        document.querySelector(".closeBtn1").onclick = closeDialog(document.querySelector(".dialog1"));
        document.querySelector(".closeBtn3").onclick = closeDialog(document.querySelector(".dialog3"));

        // 打开普通弹窗
        function openDialog(dialog) {
            return ()=>{
                dialog.show();
            }
        }

        // 打开模态弹窗,水平垂直居中,自带半透明背景(由::backdrop伪元素控制),且处于top-layer
        function openDialogModal(dialog) {
            return ()=>{
                dialog.showModal();
            }
        }

        // 关闭弹窗
        function closeDialog(dialog) {
            return ()=>{
                dialog.close();
            }
        }
    </script>
</body>
</html>

2. 效果

  • 打开弹窗1之前
    image
  • 点击后打开弹窗1
    image
  • 点击打开弹窗2
    image
  • 点击打开弹窗3,此时弹窗2也随之关闭(因为dialog元素中包裹的是form元素,且form的method=dialog)
    image
  • 关闭弹窗3,只剩弹窗1
    image
  • 关闭弹窗1
    image
posted @ 2023-01-30 12:49  pangqianjin  阅读(472)  评论(0编辑  收藏  举报