实现的关键是两个覆盖全屏的div,第一个是用于展示对话框(dialog),第二个是modal用于将背景变暗(modal)。然后点击button后dialog这个div从display:none变为正常显示,当对话框展示出来后点击modal后将modal和dialog都隐藏。

对于覆盖全屏的div使用position:fixed来固定。通过设置z-index使它们在全局之上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body,
html {
margin: 0;
padding: 0;
height: 100%;
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
font-weight: 400;
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: transparent
}

.dialog-wrapper {
z-index: 2000;
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
overflow: auto;
display: none;
transition: all 5s ease-in-out;
}

.dialog {
background: white;
position: relative;
width: 30%;
margin: 50px auto;
height: 200px;
}

.modal {
z-index: 1999;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: black;
opacity: .5;
display: none;
}
</style>
</head>

<body>
<button onclick="handle()">open</button>
<div class="dialog-wrapper">
<div class="dialog">wo shi ss</div>
</div>
<div class="modal"></div>
<script>
let dialog = document.querySelector('.dialog-wrapper');
let modal = document.querySelector('.modal');
let isOpen = false;
function handle() {
if (!isOpen) {
modal.style.display = 'inherit';
dialog.style.display = 'inherit';
isOpen = true;
}
}
dialog.addEventListener('click', () => {
if (isOpen) {
isOpen = false;
modal.style.display = 'none';
dialog.style.display = 'none';
}
})
</script>
</body>
</html>