我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。
我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。
我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。
我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?
但是,该解决方案使用jQuery。
我在绝对定位的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上时,才会执行东西。
其他回答
我用这个让它像魔法一样起作用:
function HideLayer(theEvent){
var MyDiv=document.getElementById('MyDiv');
if(MyDiv==(!theEvent?window.event:theEvent.target)){
MyDiv.style.display='none';
}
}
MyDiv标签是这样的:
<div id="MyDiv" onmouseout="JavaScript: HideLayer(event);">
<!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>
通过这种方式,当onmouseout转到子节点、孙子节点等时……的风格。Display ='none'不执行;但是当onmouseout退出MyDiv时,它会运行。
所以不需要停止传播,使用计时器等等……
谢谢例子,我可以从他们做这个代码。
希望这能帮助到一些人。
也可以这样改进:
function HideLayer(theLayer,theEvent){
if(theLayer==(!theEvent?window.event:theEvent.target)){
theLayer.style.display='none';
}
}
然后DIVs标签是这样的:
<div onmouseout="JavaScript: HideLayer(this,event);">
<!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>
所以更一般,不只是一个div,不需要添加id="…"在每一层。
如果你正在使用jQuery,你还可以使用“mouseleave”函数,它可以为你处理所有这些问题。
$('#thetargetdiv').mouseenter(do_something);
$('#thetargetdiv').mouseleave(do_something_else);
Do_something将在鼠标进入targetdiv或其任何子div时触发,do_something_else仅在鼠标离开targetdiv及其任何子div时触发。
简单地,我们可以检查e.relatedTarget是否有子类,如果为真则返回函数。
if ($(e.relatedTarget).hasClass("ctrl-btn")){
return;
}
这是为我工作的代码,我用于html5视频播放,暂停按钮切换悬停视频元素
element.on("mouseover mouseout", function(e) {
if(e.type === "mouseout"){
if ($(e.relatedTarget).hasClass("child-class")){
return;
}
}
});
有一个简单的方法可以让它起作用。元素和所有子元素都设置了相同的类名,那么:
element.onmouseover = function(event){
if (event.target.className == "name"){
/*code*/
}
}
使用onmouseleave。
或者,在jQuery中使用mouseleave()
这正是你要找的东西。例子:
<div class="outer" onmouseleave="yourFunction()">
<div class="inner">
</div>
</div>
或者,在jQuery中:
$(".outer").mouseleave(function(){
//your code here
});
这里有一个例子。