使事件处理程序忽略子级

时间:2020-03-16 22:27:37

标签: javascript html events dom-events

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

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

我希望能够在父div顶部拖动另一个div并触发ondragenter和ondragleave的事件。这可行,但是存在问题。将项目拖到孩子中时,也会触发事件。停止传播不起作用,因为它只是在子元素所在的位置创建了一个“空洞”,而问题仍然存在。

有什么办法可以完全忽略孩子?这样我就可以将项目拖入和拖出孩子,而不会发生任何事件。他们只会在物品进入父母并离开父母时才开火?

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

2 个答案:

答案 0 :(得分:1)

使用event delegation,在这里您仅在最外面的父对象上设置事件处理程序,并在那里处理所有事件。在处理程序中,您测试event.target以查看事件的源元素是什么,并且仅在该元素是您想要的元素时继续进行。

这是一个click事件示例:

document.querySelector(".parent").addEventListener("click", function(event){
  console.log("Either the parent or the child was clicked.");

  // Only react if the source of the event was the parent, not the child.
  if(event.target.classList.contains("parent")){
     alert("you clicked on the parent");
  }

});
<div>Click on both the parent and the child. Only the parent will perform the desired action.
    <div class="parent">
      I'm the parent
        <div class="child">
            I'm the child
        </div>
    </div>
</div>

答案 1 :(得分:0)

最后,我能够解决问题的方式是完全删除了onleave事件。正是造成大多数问题的原因。

因此,现在进入,我只是在检查currentTarget与以前访问的currentTarget是否不同。如果是,请禁用以前访问的currentTarget的指示器,然后激活新的currentTarget的指示器。

这实际上比我预期的要好,因为即使您离开卡,但尚未输入新卡,指示器仍会停留。这样,您就可以始终跟踪上次输入的位置。