<!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: 300px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div id="box">
<button id="btn">按钮</button>
</div>
</body>
<script>
//取消事件冒泡
var box = document.getElementById("box");
var btn = document.getElementById("btn");
box.onclick = function () {
console.log("box");
}
btn.onclick = function (event) {
var event = event || window.event;
// event.stopPropagation(); //阻止事件冒泡
if (event.stopPropagation) {
event.stopPropagation(); //非IE
} else {
event.cancelBubble = true; //兼容IE
}
console.log('btn');
}
</script>
</html>
js取消事件冒泡
于 2022-03-11 17:12:25 首次发布