【问题标题】:How to propagate event from element with higher z-index to elements under excluding click event?如何将事件从具有较高 z-index 的元素传播到不包括点击事件的元素?
【发布时间】:2021-10-07 23:23:22
【问题描述】:
我有一个包含标记的组件。 Marker 是带有图标的样式化 div。标记有 click、mouseenter 和 mouseleave 事件。当鼠标进入工具提示出现。在标记之上,我可以放置其他元素来覆盖它们。该元素具有更高的 z-index。我仍然希望能够将 (mouseenter, mouseleave) 悬停在较低的 z-index 元素(标记)上,同时防止它们被覆盖时发生单击事件。是否有任何解决方案可以仅通过少数事件或仅将某些事件排除在较高 z-index 元素上的传播中?
【问题讨论】:
标签:
javascript
html
reactjs
【解决方案1】:
<!DOCTYPE html>
<style>
#elmHigherZindexID {
width: 100px;
height: 100px;
position: absolute;
background-color: chartreuse;
z-index: 1000;
}
#elmLowerZindexID {
width: 100px;
height: 100px;
position: absolute;
background-color: cornflowerblue
}
</style>
<body>
<div id="elmHigherZindexID">HIGH</div>
<div id="elmLowerZindexID">LOW</div>
</body>
<script>
let highElmRef = document.getElementById('elmHigherZindexID');
let lowElmRef = document.getElementById('elmLowerZindexID');
highElmRef.addEventListener('click', highEventHandler);
highElmRef.addEventListener('mouseenter', highOtherEventHandler);
lowElmRef.addEventListener('mouseenter', lowEventHandler);
function highEventHandler(event) {
event.stopPropagation();
console.log('high', event);
}
function highOtherEventHandler(event) {
event.stopPropagation();
console.log('high', event);
const cusEvent = new MouseEvent('mouseenter', {
view: window,
bubbles: true,
cancelable: true
});
lowElmRef.dispatchEvent(cusEvent);
}
function lowEventHandler(event) {
event.stopPropagation();
console.log('low', event);
}
</script>
</html>