冒泡,捕获例子和解释

<!DOCTYPE HTML>
<html lang = 'en'>
	<head>
		<meta charset = 'UTF-8'/>
		<title>Document1</title>
		<style>
			.a{
    
    
				width:200px;
				height:200px;
				background-color:red;
			}
			.b{
    
    
				width:100px;
				height:100px;
				background-color:blue;
			}
		</style>
	</head>
	<body>
		<div class = 'a'>
			<div class = 'b'></div>
		</div>
		<script>
			var a = document.getElementsByTagName('div')[0];
			var b = a.children[0];
			a.onclick = function(){
    
    
				console.log('a');
			}
			//当b被点击的时候,产生冒泡,先打印b再打印a
			//冒泡就是一种执行循序,和捕获的循序相反
			b.onclick = function(e){
    
    
				var evt = e || event;
				console.log('b');
				//取消冒泡的方法,推荐(除兼容性写法)第一种
				evt.cancelBubble = 'true';
				//evt.stopPropagation();
			}
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_48727085/article/details/108237412