大家好,我是梅巴哥er
。本篇介绍 JS点击关闭按钮或盒子外,关闭盒子 的其中一种方法,以及对方法进行封装。
先看图:
上代码
<!-- demo.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="demo.css">
</head>
<body>
<div class="box">
<div class="content"></div>
<div class="x">X</div>
</div>
<script src="demo.js"></script>
</body>
</html>
/*demo.css*/
* {
padding: 0;
margin: 0;
}
.box {
display: flex;
justify-content: center;
align-items: center;
position: relative;
width: 300px;
height: 200px;
background-color: pink;
border-radius: 15px;
margin: 20px;
}
.content {
width: 150px;
height: 100px;
background-color: gold;
}
.x {
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: aqua;
text-align: center;
line-height: 30px;
font-size: 20px;
color: #fff;
}
.x:hover {
cursor: pointer;
}
/*demo.js*/
window.addEventListener('load', function() {
var $ = document.querySelector.bind(document);
var box = $(obj.box);
var x = $(obj.x);
/*点击按钮关闭盒子*/
x.addEventListener('click', function() {
box.style.display = 'none';
})
/**阻止盒子冒泡 */
box.addEventListener('click', function(e) {
e.stopPropagation();
})
/*点击框外关闭盒子*/
document.addEventListener('click', function(e) {
// log('target: ', e.target);
box.style.display = 'none';
})
})
JS部分的封装
function xFn(obj) {
var $ = document.querySelector.bind(document);
var box = $(obj.box);
/**判断是否存在关闭按钮 */
if('x' in obj) {
var x = $(obj.x);
x.addEventListener('click', function() {
box.style.display = 'none';
})
}
/**阻止盒子冒泡 */
box.addEventListener('click', function(e) {
e.stopPropagation();
})
document.addEventListener('click', function(e) {
// log('target: ', e.target);
box.style.display = 'none';
})
}
使用示例
- 有关闭按钮
var obj = {
box: '.box', // 要被关闭的盒子的类名,
x: '.x', // 关闭按钮的类名,
}
xFn(obj);
- 无关闭按钮
var obj = {
box: '.box', // 要被关闭的盒子的类名,
}
xFn(obj);
- 封装的函数会根据输入的obj对象,来自行判断是否存在关闭按钮。
说明一下
- 核心问题在于阻止box盒子的冒泡
- 更简便的方法及封装,可以查看 我的工具箱