javascript - 如何通过单击模态窗口外部正确关闭模态窗口?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">×</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>
解决方案
如果您检查页面,您将看到div
withid01
具有:
position: fixed;
width: 100%;
height: 100%;
这会div
填满整个页面,因此无论您在页面上单击什么位置,都会关闭modal
.
唯一不会触发此事件的元素是,即显示内容(标题、文本、fotter)<div class="w3-modal-content w3-card-4">
的模态内容。div
推荐阅读
- haskell - Haskell 中的二项式堆实现
- split - TypeError:尝试拆分代理时无法读取未定义的属性“拆分”
- django - Kubernetes Django 不允许的主机
- ruby-on-rails - Rails 模型测试错误/失败
- android - SecurityException:调用者不再运行
- powershell - 方法调用失败,因为 [System.ComObject] 不包含名为“IHTMLDocument3_getElementsByTagName”的方法
- python - 如何消除轴之间的间隙?
- scala - 为什么scalac盒子Int?
- c# - 记录整个屏幕
- vuejs2 - Vue Js 中的树视图动态绝对元素(上、左)