JS点击空白处关闭弹窗方法

第一种 jQuery 写法

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
<!DOCTYPE html>
<html lang="en" style="width: 100%;height: 100%;">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
border: 0;
margin: 0;
}

.dialog {
width: 100%;
height: 100%;
position: relative;
background: rgba(0, 0, 0, 0.1);
}

.dialog .dialog-content {
width: 200px;
border: 1px solid #eeeeee;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #FFF;
box-shadow: 1px 1px 10px #888888;
text-align: center;
line-height: 100px;
}
</style>
<body style="width: 100%;height: 100%;">
<div class="dialog">
<div class="dialog-content">
<p>这是弹窗</p>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).mouseup(function(e) {
var dc = $('.dialog-content'); // 目标区域,弹窗内容区域
// 如果点击的 不是目标区域 并且 不是目标区域的子元素
if (!dc.is(e.target) && dc.has(e.target).length === 0) {
// some code...
$('.dialog').hide();
}
});
</script>
</body>

</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
<!DOCTYPE html>
<html lang="en" style="width: 100%;height: 100%;">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
border: 0;
margin: 0;
}

.dialog {
width: 100%;
height: 100%;
position: relative;
background: rgba(0, 0, 0, 0.1);
}

.dialog .dialog-content {
width: 200px;
border: 1px solid #eeeeee;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #FFF;
box-shadow: 1px 1px 10px #888888;
text-align: center;
line-height: 100px;
}
</style>
<body style="width: 100%;height: 100%;">
<div class="dialog">
<div class="dialog-content" id="test">
<p>这是弹窗</p>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script>
document.addEventListener('mouseup', function(e) {
var dc = document.getElementsByClassName('dialog-content')[0];
if (dc && !dc.contains(e.target)) {
// some code...
$('.dialog').hide();
}
});
</script>
</body>

</html>
坚持原创技术分享,您的支持将鼓励我继续创作!
0%