是否有一个快速和简单的方法来做到这一点在jQuery,我错过了?

我不想使用鼠标悬停事件,因为我已经将它用于其他事情。我只需要知道鼠标在给定时刻是否在某个元素上。

我想做一些这样的事情,如果有一个“IsMouseOver”函数:

function hideTip(oi) {
    setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}

当前回答

上面Arthur Goldsmith的回答很流行也很有用:如果你在IE中将鼠标从一个元素移动到另一个元素(至少在IE 9之前),如果新元素的背景是透明的(默认情况下是透明的),你可能会遇到一些麻烦。我的解决办法是给新元素一个透明的背景图像。

其他回答

一个干净优雅的悬停检查:

if ($('#element:hover').length != 0) {
    // do something ;)
}

在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后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");
    }
});

这段代码说明了我和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); 
});

警告:is(':hover')在jquery 1.8+中已弃用。请参阅这篇文章以获得解决方案。

你也可以使用这个答案:https://stackoverflow.com/a/6035278/8843来测试鼠标是否悬停在一个元素上:

$('#test').click(function() {
    if ($('#hello').is(':hover')) {
        alert('hello');
    }
});