HTML5 dialog标签简单使用

发布时间 2023-12-20 16:08:41作者: carol2014

 HTML5 dialog标签简单使用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      dialog#test {
        width: 50vw;
        height: 30vh;
      }
      dialog#test:modal {
        background-color: rgb(160, 242, 242);
      }
      dialog#test::backdrop {
        background: rgba(0, 0, 0, 0.3);
      }
    </style>
  </head>
  <body>
    <button onclick="test.showModal()">显示模态框</button>
    <button onclick="test.show()">显示dialog标签内容</button>

    <!-- dialog标签上添加open属性 显示对话框 -->
    <dialog id="test">
      <h1>title</h1>
      <button onclick="test1.showModal()">打开第二层</button>
      <button onclick="test.close()" value="">取消</button>
    </dialog>
    <dialog id="test1">
      <form method="dialog" id="form">
        <input type="text" name="name" />
        <button type="submit" value="ok">确定</button>
        <button onclick="this.parentNode.close()">取消</button>
      </form>
    </dialog>
  </body>
</html>

<script>
  const modal = document.querySelector("#test");
  modal.addEventListener("cancel", (e) => {
    console.info("esc");
  });
  modal.addEventListener("close", (e) => {
    console.info(modal.returnValue, "closed");
  });

  const modal1 = document.querySelector("#test1");
  modal1.addEventListener("click", (e) => {
    if (e.target.nodeName.toLowerCase() == "dialog") {
      modal1.close();
    }
  });
  modal1.addEventListener("close", (e) => {
    const rtval = modal1.returnValue;
    console.info("modal1返回值", rtval);
    if (rtval == "ok") {
      const formData = new FormData(document.querySelector("#form"));
      console.log(formData.get("name"));
    }
    modal1.returnValue = "";
  });
</script>