是否有一个快速和简单的方法来做到这一点在jQuery,我错过了?
我不想使用鼠标悬停事件,因为我已经将它用于其他事情。我只需要知道鼠标在给定时刻是否在某个元素上。
我想做一些这样的事情,如果有一个“IsMouseOver”函数:
function hideTip(oi) {
setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}
是否有一个快速和简单的方法来做到这一点在jQuery,我错过了?
我不想使用鼠标悬停事件,因为我已经将它用于其他事情。我只需要知道鼠标在给定时刻是否在某个元素上。
我想做一些这样的事情,如果有一个“IsMouseOver”函数:
function hideTip(oi) {
setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}
当前回答
You can test with jQuery if any child div has a certain class. Then by applying that class when you mouse over and out out a certain div, you can test whether your mouse is over it, even when you mouse over a different element on the page Much less code this way. I used this because I had spaces between divs in a pop-up, and I only wanted to close the pop up when I moved off of the pop up, not when I was moving my mouse over the spaces in the pop up. So I called a mouseover function on the content div (which the pop up was over), but it would only trigger the close function when I moused-over the content div, AND was outside the pop up!
$(".pop-up").mouseover(function(e) { $(this).addClass("over"); }); $(".pop-up").mouseout(function(e) { $(this).removeClass("over"); }); $("#mainContent").mouseover(function(e){ if (!$(".expanded").hasClass("over")) { Drupal.dhtmlMenu.toggleMenu($(".expanded")); } });
其他回答
扩展什么'Happytime harry'说,一定要使用.data() jquery函数来存储超时id。这样,当'mouseenter'在同一个元素上被触发时,你可以很容易地检索超时id,允许你消除触发,让你的工具提示消失。
你可以使用jQuery的mouseenter和mouseleave事件。您可以在鼠标进入所需区域时设置标志,并在鼠标离开该区域时取消设置标志。
在jQuery中,你可以使用.is(':hover')
function IsMouseOver(oi)
{
return $(oi).is(':hover');
}
现在是提供OP中请求的函数的最简洁的方式。
注意:以上操作在IE8及以下版本中无效
作为在IE8中工作的不那么简洁的替代方案(如果我可以信任IE9的IE8模式),并且这样做没有触发$(…).hover(…)到处都是,也不需要知道元素的选择器(在这种情况下Ivo的答案更容易):
function IsMouseOver(oi)
{
return oi.length &&
oi.parent()
.find(':hover')
.filter(function(s){return oi[0]==this})
.length > 0;
}
你可以使用jQuery的悬停事件来手动跟踪:
$(...).hover(
function() { $.data(this, 'hover', true); },
function() { $.data(this, 'hover', false); }
).data('hover', false);
if ($(something).data('hover'))
//Hovered!
这将是最简单的方法!
function(oi)
{
if(!$(oi).is(':hover')){$(oi).fadeOut(100);}
}