我有一个组件,里面有标记。标记是带有图标的样式化 div。标记有 click、mouseenter 和 mouseleave 事件。当鼠标进入时出现工具提示。在标记的顶部,我可以放置其他元素来覆盖它们。该元素具有较高的 z-index。我仍然希望能够将鼠标悬停在较低的 z-index 元素(标记)上(mouseenter、mouseleave),同时防止它们被覆盖时发生单击事件。是否有任何解决方案可以仅传递少数事件或仅排除某些事件在较高 z 索引元素上的传播?
<!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>
是的,你可以使用 css 来实现这一点。只需将以下样式处理到父元素,该样式不会处理单击,因此将其传递给其子元素:
pointer-events: none