首页 > 解决方案 > 如何通过单击模态窗口外部正确关闭模态窗口?window.onclick 是如何工作的?

问题描述

我正在查看 W3 关于如何通过单击模式框外部来关闭模式的方法。 https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_modal_close

为什么这行得通?我认为如果你写if (event.target !== modal)来隐藏模式是正确的。关于 window.onclick 有什么我不明白的地方吗?谢谢您的帮助。

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container">
  <h2>W3.CSS Modal</h2>
  <p>In this example we demonstrate how to close the modal by clicking outside of the modal box.</p>

  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content w3-card-4">
      <header class="w3-container w3-teal"> 
        <span onclick="document.getElementById('id01').style.display='none'" 
        class="w3-button w3-display-topright">&times;</span>
        <h2>Modal Header</h2>
      </header>
      <div class="w3-container">
        <p>You have two options to close this modal:</p>
        <p>Click on the "x" or click anywhere outside of the modal!</p>
      </div>
      <footer class="w3-container w3-teal">
        <p>Modal Footer</p>
      </footer>
    </div>
  </div>
</div>

<script>
// Get the modal
var modal = document.getElementById('id01');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

标签: javascripthtmlmodal-dialog

解决方案


如果您检查页面,您将看到divwithid01具有:

position: fixed;
width: 100%;
height: 100%;

这会div填满整个页面,因此无论您在页面上单击什么位置,都会关闭modal.

唯一不会触发此事件的元素是,即显示内容(标题、文本、fotter)<div class="w3-modal-content w3-card-4">的模态内容。div


推荐阅读