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

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

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

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

当前回答

使用 evt.originalEvent.composedPath()

MouseEvent给出了鼠标最近与之交互的HTMLElement的数组。最后一个元素是最外层的(也就是说,它总是Window)。

MouseEvent composedPath()示例如下:

通过检查该数组中是否存在可点击的元素,您将知道是否在特定元素上有鼠标悬停…

$(window).on("mouseup", onMouseUp);
const $someButton = $("a.yourButton");

function onMouseUp(evt) {
  const path = evt.originalEvent.composedPath();
  if(path.indexOf($someButton[0]) !== -1){
    // released mouse over button
  }else{
    // did not release mouse over button
  }
}

其他回答

只是供未来的发现者参考。

我做了一个jQuery插件,可以做到这一点和更多。在我的插件中,要获得当前光标悬停的所有元素,只需执行以下操作:

$.cursor("isHover"); // will return jQ object of all elements the cursor is 
                     // currently over & doesn't require timer

正如我提到的,它还有很多其他用途,您可以在这里找到的jsFiddle中看到

扩展什么'Happytime harry'说,一定要使用.data() jquery函数来存储超时id。这样,当'mouseenter'在同一个元素上被触发时,你可以很容易地检索超时id,允许你消除触发,让你的工具提示消失。

在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;
}

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

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

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"));
        }
    });