<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>避免事件冒泡</title>
<style>
#box1{width:150px;height:150px;background:red;}
#box2{width:100px;height:100px;background:yellow;}
#box3{width:50px;height:50px;background:green;}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3"></div>
</div>
</div>
</body>
<script>
/*
* 避免事件冒泡,需要在函数处添加上一个参数(e|ev),然后使用e.cancelBubble对冒泡事件进行处理,赋值true禁止
* 事件冒泡,如果是false允许事件冒泡(默认)
*
* 1. 允许多个操作集中在一起处理
* 2. 让不同的对象捕获同一个事件,并调用自己的专属程序做自己的事情
*/
document.getElementById('box1').onclick = function(e){
this.style.backgroundColor = 'green';
};
document.getElementById('box2').onclick = function(e){
this.style.backgroundColor = 'red';
event.cancelBubble = true;
};
document.getElementById('box3').onclick = function(e){
this.style.backgroundColor = 'yellow';
var ev = e || event; // IE只能使用window的event属性
ev.cancelBubble = true;
};
</script>
</html>
避免事件冒泡
最新推荐文章于 2024-08-08 13:03:08 发布