是否有一个快速和简单的方法来做到这一点在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);
}
当前回答
这里有一个技术,它不依赖于jquery,并使用本机DOM匹配API。它使用厂商前缀支持回到IE9的浏览器。详情请参阅caniuse.com上的matchesselector。
首先创建matchesSelector函数,如下所示:
var matchesSelector = (function(ElementPrototype) {
var fn = ElementPrototype.matches ||
ElementPrototype.webkitMatchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector;
return function(element, selector) {
return fn.call(element, selector);
};
})(Element.prototype);
然后,检测悬停:
var mouseIsOver = matchesSelector(element, ':hover');
其他回答
一个干净优雅的悬停检查:
if ($('#element:hover').length != 0) {
// do something ;)
}
这段代码说明了我和harry想要表达的意思。当鼠标进入时,会出现一个工具提示,当鼠标离开时,它会为工具提示的消失设置一个延迟。如果鼠标在触发延迟之前输入了相同的元素,那么我们使用之前存储的数据在触发器触发之前销毁它。
$("someelement").mouseenter(function(){
clearTimeout($(this).data('timeoutId'));
$(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
var someElement = $(this),
timeoutId = setTimeout(function(){
someElement.find(".tooltip").fadeOut("slow");
}, 650);
//set the timeoutId, allowing us to clear this trigger if the mouse comes back over
someElement.data('timeoutId', timeoutId);
});
在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后onmouseover,如果数据中有值,取消超时。
删除淡出的回调数据。
使用mouseenter/mouseleave实际上成本更低,因为当child鼠标悬停/鼠标退出触发时,它们不会触发菜单。
我不能使用上面的任何建议。 为什么我更喜欢我的解决方案? 此方法检查鼠标是否在您所选择的任何时间停留在元素上。 Mouseenter和:hover很酷,但是Mouseenter只在你移动鼠标时触发,而不是当元素在鼠标下移动时触发。 :盘旋很可爱,但是…即
所以我这样做:
没有1。每次鼠标移动时,存储鼠标x, y位置, 没有2。检查鼠标是否在任何匹配查询的元素上…比如触发mouseenter事件
// define mouse x, y variables so they are traced all the time
var mx = 0; // mouse X position
var my = 0; // mouse Y position
// update mouse x, y coordinates every time user moves the mouse
$(document).mousemove(function(e){
mx = e.pageX;
my = e.pageY;
});
// check is mouse is over an element at any time You need (wrap it in function if You need to)
$("#my_element").each(function(){
boxX = $(this).offset().left;
boxY = $(this).offset().top;
boxW = $(this).innerWidth();
boxH = $(this).innerHeight();
if ((boxX <= mx) &&
(boxX + 1000 >= mx) &&
(boxY <= my) &&
(boxY + boxH >= my))
{
// mouse is over it so you can for example trigger a mouseenter event
$(this).trigger("mouseenter");
}
});
在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;
}