阻止事件冒泡的方法,包括兼容IE浏览器(e.cancelBubble )和标准浏览器(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>
.father {
position: relative;
width: 100px;
height: 100px;
background-color: aqua;
}
.son {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<div class="father" onclick="f()">
<div class="son" onclick="s()"></div>
</div>
<script>
function f() {
alert('father');
}
function s(e) {
alert('son');
// 阻止事件冒泡
var evt = e || window.event;
evt.stopPropagation
? evt.stopPropagation()
: (evt.cancelBubble = true);
}
</script>
</body>
</html>