首页 > 解决方案 > 如何将事件从具有较高 z-index 的元素传播到不包括点击事件的元素?

问题描述

我有一个组件,其中有标记。Marker 是带有图标的样式化 div。标记有 click、mouseenter 和 mouseleave 事件。当鼠标进入工具提示出现。在标记之上,我可以放置其他元素来覆盖它们。该元素具有更高的 z-index。我仍然希望能够将 (mouseenter, mouseleave) 悬停在较低的 z-index 元素(标记)上,同时防止它们被覆盖时发生单击事件。是否有任何解决方案可以仅通过少数事件或仅将某些事件排除在较高 z-index 元素上的传播中?

标签: javascripthtmlreactjs

解决方案


<!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>


推荐阅读