原生引入<dialog>元素

  <dialog>元素是html5新推出的特性,之前我用弹框都是通过ui框架来实现,今天就试一下用原生方式引用弹框。

  首先,我们在页面上要定义<dialog></dialog>标签,然后通过modal.showModal()和modal.close()的方法来分别实现弹出框的显示和关闭功能。如果你想默认页面打开弹出框,就在dialog元素里加open即可打开,是不是觉得很简单?而且在dialog框里也可以和模态框外的元素进行交互,同时模态框在关闭的时候会传个状态码,可以通过modal.returnValue来获取,这样就实现了简单的模态框展示。如果想要设置模态框的样式,可以通过dialog元素设置css样式,dialog::backdrop设置背景样式。

  具体我自己实现的代码如下:

    

<body>
    <p class="pText">haode</p>
  <button class="btn" type="button">click</button>
  <dialog id="demo-modal">
    <h3 class="modal-header">hello!</h3>
    <div class="modal-body">
      <p class="ppText"></p>
    </div>
    <footer class="modal-footer">
      <button id="close" type="button">close</button>
    </footer>
  </dialog>
    <script src="../jquery-1.12.4.js" charset="utf-8"></script>
  <script charset="utf-8">
  $(".btn").on('click', function(event) {
    event.preventDefault();
    const modal = $("#demo-modal")[0];
    modal.showModal();
    console.log("//",$(".pText").text());
    $(".ppText").text($(".pText").text());
    $("#close").on('click', function(event) {
      event.preventDefault();
      modal.close("close");
      console.log("mm",modal.returnValue);//close
    });
  });
</script>
</body>

但是,dialog元素的兼容性还是不是很好,但在谷歌上是可以显示的,可能后续会有更多浏览器支持这个特性。

posted @ 2018-01-30 11:07  Amylee_style  阅读(477)  评论(0编辑  收藏  举报