为了账号安全,请及时绑定邮箱和手机立即绑定

使事件处理程序忽略子级

使事件处理程序忽略子级

红糖糍粑 2022-05-22 10:12:04
假设我有一个类似于下面的代码(这非常简化,但相对相同的想法)<div>    <div class="parent" ondragenter="enter()" ondragleave="leave()">        <div class="child">            Stuff        </div>    </div></div>我希望能够在父 div 上拖动另一个 div 并触发 ondragenter 和 ondragleave 的事件。这有效,但有一个问题。当项目被拖入子项时,事件也会触发。停止传播不起作用,因为它只是在子元素所在的位置创建了一个“洞”,问题仍然存在。有什么办法可以完全无视孩子?所以我可以将项目拖入和拖出孩子并且不会触发任何事件;他们只在物品进入和离开父母时触发?我已经坚持了一个多星期,所以任何帮助将不胜感激。
查看完整描述

2 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

使用事件委托,您只需在最外层的父级上设置事件处理程序并在那里处理所有事件。在处理程序中,您测试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>


查看完整回答
反对 回复 2022-05-22
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

最后,我能够解决问题的方法是完全删除 onleave 事件。这是导致大多数问题的原因。

所以,现在在 onenter 上,我只是检查 currentTarget 是否与之前访问过的 currentTarget 不同。如果是,则禁用之前访问过的 currentTarget 的指标,并激活新的 currentTarget 的指标。

这实际上比我预期的要好,因为即使您离开卡,但没有输入新卡,指示器也会保持不变。这样您就可以随时跟踪您上次进入的位置。


查看完整回答
反对 回复 2022-05-22
  • 2 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号