我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。

我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。

我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。

我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?

但是,该解决方案使用jQuery。


当前回答

如果你添加(或拥有)一个CSS类或id到父元素,那么你可以这样做:

<div id="parent">
  <div>
  </div>
</div>

JavaScript:
document.getElementById("parent").onmouseout = function(e) {
  e = e ? e : window.event //For IE
  if(e.target.id == "parent") {
    //Do your stuff
  }
}

所以只有当事件在父div上时,才会执行东西。

其他回答

如果您可以访问mouseout方法中事件附加到的元素,则可以使用contains()查看事件是否。relatedTarget是否是子元素。

事件。relatedTarget是鼠标传递到的元素,如果它不是子元素,则您已经将鼠标移出了元素。

div.onmouseout = function (event) {
    if (!div.contains(event.relatedTarget)) {
        // moused out of div
    }
}

虽然你提到的解决方案使用jquery, Mouseenter和mouseleave是原生dom事件,所以你可以不使用jquery。

感谢阿姆贾德·马萨德,他激励了我。

我有以下解决方案,似乎在IE9, FF和Chrome和代码很短(没有复杂的闭包和横向子东西):

    DIV.onmouseout=function(e){
        // check and loop relatedTarget.parentNode
        // ignore event triggered mouse overing any child element or leaving itself
        var obj=e.relatedTarget;
        while(obj!=null){
            if(obj==this){
                return;
            }
            obj=obj.parentNode;
        }
        // now perform the actual action you want to do only when mouse is leaving the DIV
    }

对于在大多数情况下都有效的更简单的纯CSS解决方案,可以通过将子指针事件设置为none来删除它们

.parent * {
     pointer-events: none;
}

浏览器支持IE11+

尝试mouseleave ()

例子:

<div id="parent" mouseleave="function">
   <div id="child">

   </div>
</div>

;)