在jQuery中关闭模式弹出窗口

问题描述 投票:0回答:1

我有一幅图像,一旦单击它就会显示一个模态。如果我在模态窗口之外单击,它会很好地关闭,但是,如果我单击已放入X标记中的span,它不会关闭。任何帮助,将不胜感激!

var modal = document.getElementById("myModal1");
var btn = document.getElementById("myBtn1");
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
<button id="myBtn1" class="button2"><img class="box" src="image.png"></button>
<div id="myModal1" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <h2>Some text in the Modal..</h2>
    More text in modal...
  </div>
</div>
javascript html modal-dialog
1个回答
0
投票

这里是您要寻找的完整示例

var modal = document.getElementById("myModal1");
var btn = document.getElementById("myBtn1");
var close = document.querySelector("#myModal1 .close");



// When the user clicks anywhere outside of the modal, close it
btn.addEventListener("click",function() {
  modal.style.display = "block";
}) 
close.addEventListener("click",function() {
  modal.style.display = "none";
}) 
window.addEventListener("click",function(e) {
  const inside = modal.contains(e.target);
  if (!inside && e.target !== btn) {
    modal.style.display = "none";
  }
})
.modal { display:none }
<button id="myBtn1" class="button2">Click</button>
<div id="myModal1" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <h2>Some text in the Modal..</h2>
    More text in modal...
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.