阻止事件冒泡的两种方式

  • Post author:
  • Post category:其他


事件冒泡:开始时由最具体的元素接收,然后逐级向上传播到DOM最顶层节点。

事件冒泡本身的特性,会带来的坏处,也会带来的好处。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.father {
				width: 100px;
				height: 100px;
				background-color: pink;
			}
			
			.son {
				width: 50px;
				height: 50px;
				background-color: skyblue;
			}
		</style>
	</head>
	<body>
		<div class="father">
			<div class="son">
				
			</div>
		</div>
		<script type="text/javascript">
			var son = document.querySelector('.son');
			son.addEventListener('click', function(e) {
				alert('son');
				e.stopPropagation();  //stop  停止 Propagation传播   这种用的更多一点
				e.cancelBubble = true;  //非标准cancle 取消 bubble 泡泡
			}, false);
			
			
			var father = document.querySelector('.father');
			father.addEventListener('click', function(){
				alert('father');
			}, false);
			document.addEventListener('click', function() {
				alert('document');
			})
		</script>
	</body>
</html>

stopPropagation();  //stop  停止 Propagation传播   这种用的更多一点

cancelBubble = true;  //非标准cancle 取消 bubble 泡泡

注意它添加在哪里,就仅仅能取消所在位置的事件冒泡  上例中 假如点击father会继续冒泡  想要阻止father的冒泡 就需要在father的点击事件里添加相关代码。



版权声明:本文为m0_62962469原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。