原生js事件的三个阶段:捕获、执行、冒泡

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#box1 {
			width: 300px;
			height: 300px;
			background-color: pink;
		}
		#box2 {
			width: 200px;
			height: 200px;
			background-color: orange;
		}
		#box3 {
			width: 100px;
			height: 100px;
			background-color: red;
		}
	</style>
</head>
<body>
	<div id="box1">box1
		<div id="box2">box2
			<div id="box3">box3</div>
		</div>
	</div>

	<script src="js/common.js"></script>
	<script>
		// addEventListener第三个参数的作用
		var box1 = my$('box1');
		var box2 = my$('box2');
		var box3 = my$('box3');

		var arr = [box1, box2, box3];
		// for (var i=0; i < arr.length; i++) {
		// 	arr[i].addEventListener('click', function () {
		// 		console.log(this.id);  // 点击最里面的元素时: box3  box2  box1
		// 	}, false);  // addEventListener第三个参数为false时,事件冒泡,从最里层的元素往外传递
		// }

		// document.body.addEventListener('click', function () {
		// 	console.log('body'); // 点击最里面的元素时:box3  box2  box1 body
		// }, false);


		// for (var i=0; i < arr.length; i++) {
		// 	arr[i].addEventListener('click', function () {
		// 		console.log(this.id);  // 点击最里面的元素时:box1  box2  box3
		// 	}, true);  // addEventListener第三个参数为true时,事件捕获,从最外层的元素开始
		// }

		// document.body.addEventListener('click', function () {
		// 	console.log('body'); // 点击最里面的元素时:body  box1  box2  box3
		// }, true);

		// 事件的三个阶段:捕获、执行当前点击的元素、冒泡
		// onclick	只有事件冒泡
		// onclick验证
		for (var i=0; i < arr.length; i++) {
			arr[i].onclick = function () {
				console.log(this.id);
			};  
		}

		document.body.onclick = function () {
			console.log('body'); 
		};

		document.onclick = function () {
			console.log('document'); // 点击最里面的元素时:box3  box2  box1 body document
		}
		// attachEvent() 只有两个参数,只有事件冒泡


	</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值