我有两个重叠的兄弟姐妹,像这样:
document.querySelector("#item1").addEventListener('mouseup',()=>{
console.log("Mouseup item 1!");
});
document.querySelector("#item2").addEventListener('mouseup',()=>{
console.log("Mouseup item 2!")
},true);
#item1{
height:10rem;
width:10rem;
background-color:red;
position:absolute;
z-index:-2;
}
#item2{
height:10rem;
width:10rem;
background-color:green;
position:relative;
top:2rem;
}
<div id="item1"></div>
<div id="item2"></div>
每当我在item2上设置mouseup
时,如果鼠标在item1内,我希望item1 mouseup事件也被触发
(基本上我希望mouseup
在鼠标所在的任何div上被触发,无论哪个div重叠什么)
我如何做到这一点?
使用@Teemu在评论中指出的elementsFromPoint
,我想出了这个:
document.querySelector("#wrapper").addEventListener('mouseup', (event) => {
let els = document.elementsFromPoint(event.clientX, event.clientY);
els.forEach(el => {
if (el.id != '' && el.id != 'wrapper')
console.log(el.id)
})
});
#item1 {
height: 10rem;
width: 10rem;
background-color: red;
position: absolute;
}
#item2 {
height: 10rem;
width: 10rem;
background-color: green;
position: relative;
top: 2rem;
}
#wrapper {
background-color: blue;
height: 20rem;
width: 20rem;
}
<div id="wrapper">
<div id="item1"></div>
<div id="item2"></div>
</div>