我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。
我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。
我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。
我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?
但是,该解决方案使用jQuery。
我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。
我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。
我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。
我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?
但是,该解决方案使用jQuery。
当前回答
我认为Quirksmode有你需要的所有答案(不同的浏览器冒泡行为和mouseenter/mouseleave事件),但我认为最常见的结论是,事件冒泡混乱的使用框架,如JQuery或Mootools(有mouseenter和mouseleave事件,这正是你直觉会发生的)。
看看他们是怎么做的,如果你想的话,自己做吧 或者你也可以用事件部分(及其依赖项)创建自定义的“精益”版本的Mootools。
其他回答
感谢阿姆贾德·马萨德,他激励了我。
我有以下解决方案,似乎在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
}
var elem = $('#some-id');
elem.mouseover(function () {
// Some code here
}).mouseout(function (event) {
var e = event.toElement || event.relatedTarget;
if (elem.has(e).length > 0) return;
// Some code here
});
使用onmouseleave。
或者,在jQuery中使用mouseleave()
这正是你要找的东西。例子:
<div class="outer" onmouseleave="yourFunction()">
<div class="inner">
</div>
</div>
或者,在jQuery中:
$(".outer").mouseleave(function(){
//your code here
});
这里有一个例子。
如果您可以访问mouseout方法中事件附加到的元素,则可以使用contains()查看事件是否。relatedTarget是否是子元素。
事件。relatedTarget是鼠标传递到的元素,如果它不是子元素,则您已经将鼠标移出了元素。
div.onmouseout = function (event) {
if (!div.contains(event.relatedTarget)) {
// moused out of div
}
}
有一个简单的方法可以让它起作用。元素和所有子元素都设置了相同的类名,那么:
element.onmouseover = function(event){
if (event.target.className == "name"){
/*code*/
}
}