<!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>
原生js事件的三个阶段:捕获、执行、冒泡
最新推荐文章于 2023-09-07 13:48:39 发布