event.target 在这个 W3 学校模态示例中指的是什么?



我不明白这个例子:

[code]
<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
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";
}
else
alert("Mongoose");
}
</script>
</body>
</html>
[/code]

我不明白的部分是:

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

我本以为既然它应该在模态之外点击,那么它会是

if (event.target !=modal)

event.target指的是什么?

在W3schools代码示例中,我认为(event.target == modal)中的modal实际上指的是var(见下文(,它本身指的是背景div idmyModal

<!-- The Modal -->
<div id="myModal" class="modal">

和:

// Get the modal
var modal = document.getElementById('myModal');

(W3schools示例中divmyModal名也是模态的,这真的非常非常令人困惑(。

实际的模态"盒子"div的类是模态内容

包含"background"div 类的较大部分是模态的,它填充了模框本身之外的浏览器窗口中剩余的负空间(见下图(。

https://i.stack.imgur.com/rEqn0.jpg

https://i.stack.imgur.com/kd5K7.jpg

它知道模态框外的内容被单击,因为它检测到背景div 被单击。后台div 的id是 myModal,它存储在varmodal 中,这是(event.target == modal)中的modal

注意:我不是模态专家,所以我的理解可能有点偏差(如果有人有任何更正,请随时发表评论或发布更好的答案(,但我希望这为您指明正确的方向,以理解这个令人困惑的例子。

最新更新