Document
.box1 {
width: 800px;
height: 400px;
background: red;
margin: 0 auto;
}
.box2 {
width: 500px;
height: 300px;
background: green;
margin: auto;
}
.box3 {
width: 300px;
height: 100px;
background: blue;
margin: auto;
}
window.onload = function() {
var box1 = document.getElementsByClassName("box1")[0];
var box2 = document.getElementsByClassName("box1")[0];
var box3 = document.getElementsByClassName("box1")[0];
window.addEventListener('click', function() {
console.log("捕获阶段:window执行捕获事件");
}, true);
document.body.addEventListener('click', function() {
console.log("捕获阶段:body执行捕获事件");
}, true);
window.addEventListener('click', function() {
console.log("冒泡阶段:window执行冒泡事件");
}, false);
document.body.addEventListener('click', function() {
console.log("冒泡阶段:body执行冒泡事件");
}, false);
box1.addEventListener('click', function() {
/* */
console.log("捕获阶段:box1执行捕获事件");
}, true);
box2.addEventListener('click', function() {
/* */
console.log("捕获阶段:box2执行捕获事件");
}, true);
box3.addEventListener('click', function() {
/* */
console.log("捕获阶段:box3执行捕获事件");
}, true);
box1.addEventListener('click', function() {
/* */
console.log("冒泡阶段:box1执行冒泡事件");
}, true);
box2.addEventListener('click', function() {
/* */
console.log("冒泡阶段:box2执行冒泡事件");
}, true);
box3.addEventListener('click', function() {
/* */
console.log("冒泡阶段:box3执行冒泡事件");
}, true);
}
链:http://www.jianshu.com//p/062d40ea88ce
执行结果如下:
这里说明一下当执行到达目标阶段时,可能出现冒泡事件比捕获事件先执行,这种情况是因为冒泡事件比捕获事件先注册。
链接:http://www.jianshu.com//p/062d40ea88ce
网友评论