事件冒泡机制和如何阻止冒泡

一、事件冒泡

在浏览器客户端应用平台,基本上都是以事件驱动的,就是说去执行某个事件,然后做出相应的操作。

事件冒泡就是在事件开始时,由最具体的元素(文档中最底层的那个节点)接受,然后逐级向上传播到最不具体的节点(文档)。比如说,在一个页面有一个div元素,加上一个点击事件,在点击事件触发的时候,它的传递过程就是由div→body→html→document(老版本暂且不谈),它会沿着DOM树逐级的传递。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.outer{
				width: 200px;
				height: 200px;
				background: red;
				z-index: 1;
			}
			.cent{
				width: 100px;
				height: 100px;
				background: blue;
				position: absolute;
				right: 0;
				left: 0;
				bottom: 0;
				top: 0;
				margin:auto;
				z-index: 2;
			}
			.insert{
				width: 50px;
				height: 50px;
				background: orange;
				position: absolute;
				right: 0;
				left: 0;
				bottom: 0;
				top: 0;
				margin:auto;
				z-index: 3;
			}
			div{
				position: relative;
			}
		</style>
	</head>
	<body>
		<div class="outer">
			<div class="cent">
				<div class="insert"></div>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		var Outer=document.getElementsByClassName("outer")[0];
		var Cent=document.getElementsByClassName("cent")[0];
		var Insert=document.getElementsByClassName("insert")[0];
		var aBody=document.getElementsByTagName("body")[0];
		Outer.onclick=function(){
			console.log("aaa")
		}
		Cent.onclick=function(){
			console.log("bbb")
		}
		Insert.onclick=function(){
			console.log("ccc")
		}
		aBody.onclick=function(){
			console.log("我是body")
		}
	</script>
</html>

在这个嵌套的层级关系中,点击Insert这个元素的时候会依次输出ccc、bbb、aaa、我是body,这就是事件冒泡机制。

二、阻止事件冒泡

阻止事件冒泡的方法有两种:

  1. storpPrapagation()  // 不支持IE低版本
  2. cancelBubble=true

 兼容写法:

 if(event.storpPrapagation){

           event.storpPrapagation();

}else{

           cancelBubble=true;

}

            还拿上面的举例:

<script type="text/javascript">
		var Outer=document.getElementsByClassName("outer")[0];
		var Cent=document.getElementsByClassName("cent")[0];
		var Insert=document.getElementsByClassName("insert")[0];
		var aBody=document.getElementsByTagName("body")[0];
		Outer.onclick=function(e){
			var evt=e||event;
			evt.stopPropagation();
			console.log("aaa")
		}
		Cent.onclick=function(){
			console.log("bbb")
		}
		Insert.onclick=function(){
			console.log("ccc")
		}
		aBody.onclick=function(){
			console.log("我是body")
		}
	</script>

在outer元素上阻止冒泡,控制台输出的就只有ccc、bbb、aaa,而没有‘我是body’,就是因为冒泡事件在执行到outer元素的时候被阻止了,所以body并没有执行点击事件。

点滴的积累,最终会形成汪洋大海。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值