事件对象4e:e.stoppropagation():阻止事件继续传播 ——制作弹出层:点击指定位置框框弹出,点击其它位置页面关闭
简单理解:
在这里插入代码片
<!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>
<style>
#box {
width: 200px;
height: 200px;
margin: 100px;
background-color: rgb(194, 194, 99);
}
#box1 {
width: 100px;
height: 100px;
margin: 100px;
position: absolute;
background-color: pink;
}
h1 {
background-color: green;
}
</style>
</head>
<body>
<div id="box"></div>
<h1>hello</h1>
<div id="box1"></div>
</body>
<script>
var oBox = document.getElementById('box')
var oBox1 = document.getElementById('box1')
var oH1 = document.querySelector('h1')
oBox.onclick = function (e) {
console.log('box');
oBox1.style.backgroundColor = 'green'
e.stopPropagation()
}
oH1.onclick = function (e) {
console.log('h1');
oBox1.style.backgroundColor = 'red'
e.stopPropagation()
}
document.onclick = function (e) {
console.log('document');
oBox1.style.backgroundColor = 'blue'
}
oBox1.onclick = function (e) {
console.log('box1');
e.stopPropagation()
}
</script>
</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>事件对象之阻止事件继续传播e.stopPropagation()</title>
<style>
#box {
width: 200px;
height: 200px;
margin: 100px;
background-color: green;
position: absolute;
display: none;
}
</style>
</head>
<body>
<!-- 制作弹出层:点击按钮显示弹出层,点击其它地方弹出层关闭 -->
<button>弹出</button>
<div id="box"></div>
</body>
<script>
var obtn = document.querySelector('button')
var obox = document.getElementById('box')
obtn.onclick = function (e) {
// 阻止该事件传播到document
e.stopPropagation();
box.style.display = 'block'
}
document.onclick = function (e) {
box.style.display = 'none'
}
// 点击弹出层内部时,不能关闭弹出层
obox.onclick = function (e) {
// 阻止事件传播到document
e.stopPropagation();
}
</script>
</html>