html模态弹出层简单实现例子

模态框就是弹出后,在其取消掉前不再允许操作其他窗口。下面是一个简单的js实现的模态框例子。

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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.2);
display: none;
}
#diag {
background-color: pink;
width: 200px;
height: 100px;
position: fixed;
left: 50%;
top: 30%;
display: none;
}
#close {
position: absolute;
top: 5px;
right: 5px;
}
</style>
<title>实现模态弹出框</title>
</head>
<body>
<button id="btn_diag">弹出</button>
<button id="btn_test">测试</button>
<div id="mask">
</div>
<div id="diag">
<div id="close">X</div>
</div>
</body>
<script>
window.onload = function() {
var btn_diag = document.getElementById('btn_diag');
var btn_test = document.getElementById('btn_test');
var diag = document.getElementById('diag');
var mask = document.getElementById('mask');
var close = document.getElementById('close');
btn_diag.onclick = function() {
mask.style.display = 'block';
diag.style.display = 'block';
}
btn_test.onclick = function() {
alert(btn_test.innerText);
}
close.onclick = function() {
mask.style.display = 'none';
diag.style.display = 'none';
}
}
</script>
</html>