事件捕获与事件冒泡
向下是捕获阶段
---------------
| ^
---------------
V ^
---------------
V |
---------------
向上是冒泡阶段
事件对象:
事件触发时包含了事件发生的元素和属性信息
var div3 = document.getElementById("div3");
div3.addEventListener("click", function (e) {
var e = e || window.event; // IE 8 window.event arguments[0]
console.log(e);
}, false); // true: 捕获, false: 冒泡(默认)
事件的周期
--------------------
div1 |
--------------- |
div2 | |
-------- | |
div3 | | |
-------- | |
--------------- |
--------------------
<style>
#div1 {
width: 300px;
height: 300px;
background-color: green;
}
#div2 {
width: 200px;
height: 200px;
background-color: blue;
}
#div3 {
width: 100px;
height: 100px;
background-color: grey;
}
</style>
<div id="div1">
div1
<div id="div2">
div2
<div id="div3">div3</div>
</div>
</div>
<script>
// 事件对象:时间触发时包含了事件发生的元素和属性信息
var div3 = document.getElementById("div3");
div3.addEventListener(
"click",
function (e) {
console.log("div3");
},
false
);
var div2 = document.getElementById("div2");
div2.addEventListener(
"click",
function (e) {
console.log("div2");
},
false
);
var div1 = document.getElementById("div1");
div1.addEventListener(
"click",
function (e) {
console.log("div1");
},
false
);
/**
* 点击div 3
*
* div3 -> div2 -> div1
*/
</script>
阻止冒泡:
e.stopPropagation()
e.cancelBubble = true // IE8
事件冒泡的应用:事件委托
<div id="demo">
<li>aaaaaa</li>
<li>bbbbbb</li>
<li>cccccc</li>
</div>
<script>
// 事件委托
var demo = document.getElementById("demo");
demo.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == "li") {
console.log(e.target.innerHTML);
}
}, false );
</script>