jQuery:检查鼠标是否悬停在元素上

4
我正在处理以下情况: 我有一个带热点的图像映射。当你在图像映射上鼠标悬停在<area>时,会显示一个<div class="info-panel">。这个div会覆盖<area>,所以当<div class="info-panel">的mouseleave事件发生时,该div会被隐藏。
这基本上是有效的,但偶尔会出现问题,例如如果你移动鼠标太快,div会一直保持显示状态。我认为这可能是<area><div>相交的小实例。我不用担心它,只是客户指出了这个问题。
我能想到的唯一可靠的解决方法是,在鼠标移动时检查是否有信息窗口处于显示状态。如果有,则检查鼠标当前是否在其上方 - 如果不是,则将其隐藏。这将确保在鼠标未悬停在信息窗口上时,信息窗口永远不会显示。
我的问题是:如何检查当前鼠标位置是否在信息窗口上方?需要注意的是,这是为了异常情况而不是规则,我不能确定信息窗口是否可见?
3个回答

9
当鼠标移出时,设置一个定时器,例如1秒后关闭所有窗口。当鼠标移入时,请确保删除该定时器...因此,定时器仅在鼠标移出时设置。类似于:
var timer; 
$(".window").mouseout(function(){
    $(".window").hide(); // regular hide

    // run the same thing after 1 second
    // to catch windows that are still open
    timer = setTimeout(function(){
        $(".window").hide(); // regular hide
    }, 1000); // 1 second
});

// be sure to remove the timer when you mouseover
$(".window").mouseover(function(){
    clearTimeout(timer);

    // other stuff
});

2

试试这个:

function show_info (thelink,info_panel) {   
    var timer; 
    timer = setTimeout(function(){
        $(info_panel).stop(true, true).fadeIn('normal');
    }, 300); 
    $(thelink).mouseout(function(){ clearTimeout(timer); });
}

function hide_info (resim) {
    $(info_panel).stop(true, true).fadeOut('normal');
}

而HTML代码应该是:

<a href="#" id="thelink" onmouseover="show_tipbox('#thelink','#info_panel');">The link</a>
<div id="info_panel" onmouseout="hide_tipbox('#info_panel');">Info Panel Content</div>

2

不要使用mouseover,而是使用mouseentermouseleave作为事件处理程序。


我正在使用mouseover来处理区域,mouseleave来处理div...不幸的是,在这里使用mouseenter没有任何区别。 - pingu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接