【问题标题】:Element inside div should not interfere on the event handlerdiv 内的元素不应干扰事件处理程序
【发布时间】:2015-01-31 18:23:47
【问题描述】:

我有一个 div,里面有一个 p。该段落在视觉上位于 div 上方。我的事件处理程序受到段落的影响。

这是我的事件处理程序:

$("#container-map").on("mouseover mouseleave", ".ct-symbol", function() {
    $(this).toggleClass("active-b");
});

所以,当我在 div 上移动鼠标时,如果我跨过段落,它将切换类。我想要的是只有在我进入/离开 div 时才切换类。我也试过用这个:

$("#container-map").on("mouseover mouseleave", ".ct-symbol", ".ct-symbol p" function() {
    $(this).toggleClass("active-b");
});

但是现在,一旦我将鼠标移到段落上方,它就会切换两次...

【问题讨论】:

  • 要么检查函数中的正确元素,要么使用event.stopPropagation()停止事件传播

标签: javascript jquery events handler


【解决方案1】:
$("#container-map").on("mouseenter mouseleave", ".ct-symbol", function() {
    if (this.id == "container-map")
    {
       $(this).toggleClass("active-b");
    }
});

应该可以。它仅在this 与 div 具有相同 id 时触发。

【讨论】:

    【解决方案2】:

    你必须使用mouseenter 而不是mouseover

    $("#container-map").on("mouseenter mouseleave", ".ct-symbol" function() {
        $(this).toggleClass("active-b");
    });
    

    【讨论】:

      【解决方案3】:

      如果您想要的是您的 active-b 类仅在您离开/进入时受到影响。

      您需要使用 mouseenter 而不是 mouseover

      $("#container-map").on("mouseenter mouseleave", ".ct-symbol", function() {
          $(this).toggleClass("active-b");
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多