1.先创建一个DOM叔伯,一个DOM父子
<span>
<div id="uncle-up" style="position:absolute;background-color: royalblue; width: 100px; height: 100px;"></div>
<div id="uncle-down" style="position:absolute;background-color: red; width: 20px; height:20px;"></div>
</span>
<span>
<div id="father" style="background-color: royalblue; width: 100px; height: 100px;margin:0 auto">
<div id="son" style="background-color: red; width: 20px; height:20px;;margin:0 auto"></div>
</div>
</span>
//对应的鼠标事件
document.getElementById("uncle-up").onmousedown = function () {
console.log("uncle-up")
}
document.getElementById("uncle-down").onmousedown = function () {
console.log("uncle-down")
}
document.getElementById("father").onmousedown = function () {
console.log("father")
}
document.getElementById("son").onmousedown = function () {
console.log("son")
}
2.分别点击重叠部分,看控制台输出
1.uncle-up---控制台输出:uncle-down
2.son-----控制台输出:son; father
结果汇总:
DOM重叠之“叔伯”鼠标事件时,下面的dom会覆盖上面的dom,且鼠标事件只会在最下面一层生效
DOM重叠之“父子”鼠标事件时,先触发子dom的事件再触发父dom事件
3.针对两个结果:
3.1:如何在"叔伯"DOM重叠时,让上面的dom也能触发事件?
//方式1:通过z-index属性更改图层位置,值越大在上层;现在点击控制台输出:uncle-up
<span>
<div id="uncle-up" class="canline" style="background-color: rgba(230, 230, 233, 0.644); width: 100px; height: 100px;z-index: 2;"></div>
<div id="uncle-down" class="canline" style="background-color: red; width: 20px; height:20px;z-index: 1;"></div>
</span>
//方式2:通过pointer-events:none;属性指定当前图层的点击事件穿透:现在点击控制台输出:uncle-up
<span>
<div id="uncle-up" class="canline" style="background-color: rgba(230, 230, 233, 0.644); width: 100px; height: 100px"></div>
<div id="uncle-down" class="canline" style="background-color: red; width: 20px; height:20px;pointer-events:none"></div>
</span>
3.2:如何阻断“父子”DOM的父DOM事件?
//阻止事件冒泡:event.stopPropagation()
//在子DOM对应的事件中添加阻止事件冒泡
document.getElementById("son").onmousedown = function (event) {
**event.stopPropagation();**
console.log("son")
}