1. 程式人生 > >addEventListener 冒泡 和 捕獲

addEventListener 冒泡 和 捕獲

#div1 {
    width: 500px;
    height: 300px;
    background-color: #4fc08d;
    display:flex;
    justify-content:center;
    align-items:center;
}

#div2 {
    width: 200px;
    height: 200px;
    background-color: red;
}

 

<div id="div1">
    <div id="div2"></div>
</div>

 

var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");

div1.addEventListener("click", function () {
    console.log("div1");
}, true);
div2.addEventListener("click", function () {
    console.log("div2");
}, true);

用滑鼠點選div2  列印順序為: div1  div2      // 捕獲

 

var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");

div1.addEventListener("click", function () {
    console.log("div1");
});
div2.addEventListener("click", function () {
    console.log("div2");
});

用滑鼠點選div2  列印順序為: div2  div1      //冒泡