是否有一个快速和简单的方法来做到这一点在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);
}
当前回答
我不能使用上面的任何建议。 为什么我更喜欢我的解决方案? 此方法检查鼠标是否在您所选择的任何时间停留在元素上。 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,并使用本机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');
我经常看到超时用于此,但在事件的上下文中,您不能像这样查看坐标吗?:
function areXYInside(e){
var w=e.target.offsetWidth;
var h=e.target.offsetHeight;
var x=e.offsetX;
var y=e.offsetY;
return !(x<0 || x>=w || y<0 || y>=h);
}
根据上下文,您可能需要在调用areXYInside(e)之前确保(this==e.t target)。
我正在考虑在dragLeave处理程序中使用这种方法,以确认dragLeave事件不是由进入子元素触发的。如果您没有以某种方式检查您是否仍然在父元素中,那么您可能会错误地执行仅在真正离开父元素时才执行的操作。
编辑:这是一个很好的想法,但并不能始终如一地工作。也许要做一些小调整。
我已经在另一个问题中回答了这个问题,以及你可能需要的所有细节:
使用jQuery检测IF悬停在元素上(在撰写本文时有99个赞)
基本上,你可以这样做:
var ishovered = oi.is(":hover");
只有当oi是一个包含单个元素的jQuery对象时,这才有效。如果有多个元素匹配,你需要应用到每个元素,例如:
var hoveredItem = !!$('ol>li').filter(function() { return $(this).is(":hover"); });
// not .filter(':hover'), as we can't apply :hover on multiple elements
这是从jQuery 1.7开始测试的。
这将是最简单的方法!
function(oi)
{
if(!$(oi).is(':hover')){$(oi).fadeOut(100);}
}
在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后onmouseover,如果数据中有值,取消超时。
删除淡出的回调数据。
使用mouseenter/mouseleave实际上成本更低,因为当child鼠标悬停/鼠标退出触发时,它们不会触发菜单。