# 16.手写一个弹窗功能
- 遮罩层为父子关系
/* html */
<div class="container">
<div id="popup">
<span>主题</span>
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
/* css */
.container {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
opacity: 0.5;
z-index: 1;
background-color: blueviolet;
}
#popup {
padding: 50px;
display: flex;
justify-content: center;
position: absolute;
align-items: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: aquamarine;
z-index: 2;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* JS */
//第一种方法,通过判断e.target,即触发事件的节点。
let container = document.getElementsByClassName("container")[0];
let popup = document.getElementById("popup");
container.addEventListener(
"click",
(e) => {
if (e.target == container) {
//
container.style.display = "none";
}
},
false
);
//第二种方法,阻止子节点的冒泡事件。
let container = document.getElementsByClassName("container")[0];
let popup = document.getElementById("popup");
container.addEventListener("click", (e) => {
container.style.display = "none";
});
popup.addEventListener("click", (e) => {
event.cancelBubble = true;
event.stopPropagation;
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
← 15.手写 JsonP 17.函数柯里化 →