#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 //冒泡