点击模态

时间:2016-01-18 23:34:15

标签: javascript modal-dialog

当单击模态中的关闭按钮时,我的模态弹出窗口关闭,但我希望它们在用户单击窗口中的任何位置时关闭。到目前为止我在那里有这个javascript:

    var span = document.getElementsByClassName("close");
var btn = document.getElementsByClassName("click-to-open");
var modal=document.getElementById("modal-window-4");

for (var i = 0; i < btn.length; i++) {
  var thisBtn = btn[i];
      thisBtn.addEventListener("click", function(){
        var modal = document.getElementById(this.dataset.modal);
        modal.style.display = "block";
    }, false);

}

for (var j = 0; j < span.length; j++) {
  var closeThis = span[j];
      closeThis.addEventListener("click", function(){
        var closeModal = document.getElementById(this.dataset.modal);
        closeModal.style.display = "none";
    }, false);
}



window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

Codepen:http://codepen.io/FelixB/pen/QyOpoo

这里的其他帖子涉及jQuery,但我已经将这个用于直接的javascript,所以我希望有人知道一种简单的方法来实现这一点。

1 个答案:

答案 0 :(得分:0)

我使用body onload事件来初始化其余的事件处理程序。一旦面板可见,我就设置了点击处理程序。它似乎对我有用。

                function init() {
                    var span = document.getElementsByClassName("close");
                    var btn = document.getElementsByClassName("click-to-open");
                    var modal = document.getElementById("modal-window-4");

                    for (var i = 0; i < btn.length; i++) {
                        var thisBtn = btn[i];
                        thisBtn.addEventListener("click", function () {
                            var modal = document.getElementById(this.dataset.modal);
                            modal.style.display = "block";
                            modal.addEventListener("click", function () { modal.style.display = "none"; modal.removeEventListener("click"); });
                        }, false);

                    }

                }

和html

      <body  onload="init()">
      <!-- and the rest of  your code -->
      </body>