猿问

使事件处理程序忽略子级

假设我有一个类似于下面的代码(这非常简化,但相对相同的想法)


<div>

    <div class="parent" ondragenter="enter()" ondragleave="leave()">

        <div class="child">

            Stuff

        </div>

    </div>

</div>

我希望能够在父 div 上拖动另一个 div 并触发 ondragenter 和 ondragleave 的事件。这有效,但有一个问题。当项目被拖入子项时,事件也会触发。停止传播不起作用,因为它只是在子元素所在的位置创建了一个“洞”,问题仍然存在。


有什么办法可以完全无视孩子?所以我可以将项目拖入和拖出孩子并且不会触发任何事件;他们只在物品进入和离开父母时触发?


我已经坚持了一个多星期,所以任何帮助将不胜感激。


红糖糍粑
浏览 99回答 2
2回答

梵蒂冈之花

使用事件委托,您只需在最外层的父级上设置事件处理程序并在那里处理所有事件。在处理程序中,您测试event.target以查看事件的源元素是什么,并且仅当元素是您想要的元素时才继续。这是一个click事件示例:document.querySelector(".parent").addEventListener("click", function(event){&nbsp; console.log("Either the parent or the child was clicked.");&nbsp; // Only react if the source of the event was the parent, not the child.&nbsp; if(event.target.classList.contains("parent")){&nbsp; &nbsp; &nbsp;alert("you clicked on the parent");&nbsp; }});<div>Click on both the parent and the child. Only the parent will perform the desired action.&nbsp; &nbsp; <div class="parent">&nbsp; &nbsp; &nbsp; I'm the parent&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; I'm the child&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div>

胡子哥哥

最后,我能够解决问题的方法是完全删除 onleave 事件。这是导致大多数问题的原因。所以,现在在 onenter 上,我只是检查 currentTarget 是否与之前访问过的 currentTarget 不同。如果是,则禁用之前访问过的 currentTarget 的指标,并激活新的 currentTarget 的指标。这实际上比我预期的要好,因为即使您离开卡,但没有输入新卡,指示器也会保持不变。这样您就可以随时跟踪您上次进入的位置。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答