如何检查鼠标是否在 jQuery 中的元素上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1273566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:04:16  来源:igfitidea点击:

How do I check if the mouse is over an element in jQuery?

jquerymouseover

提问by Steve Wortham

Is there a quick & easy way to do this in jQuery that I'm missing?

在我缺少的 jQuery 中,是否有一种快速简便的方法可以做到这一点?

I don't want to use the mouseover event because I'm already using it for something else. I just need to know if the mouse is over an element at a given moment.

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

I'd like to do something like this, if only there was an "IsMouseOver" function:

我想做这样的事情,只要有一个“IsMouseOver”功能:

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

采纳答案by mothmonsterman

Set a timeout on the mouseout to fadeout and store the return value to data in the object. Then onmouseover, cancel the timeout if there is a value in the data.

将鼠标移出超时设置为淡出并将返回值存储到对象中的数据。然后onmouseover,如果数据中有值就取消超时。

Remove the data on callback of the fadeout.

删除淡出回调的​​数据。

It is actually less expensive to use mouseenter/mouseleave because they do not fire for the menu when children mouseover/mouseout fire.

使用 mouseenter/mouseleave 实际上更便宜,因为当孩子 mouseover/mouseout 触发时,它们不会为菜单触发。

回答by Arthur Goldsmith

This code illustrates what happytime harryand I are trying to say. When the mouse enters, a tooltip comes out, when the mouse leaves it sets a delay for it to disappear. If the mouse enters the same element before the delay is triggered, then we destroy the trigger before it goes off using the data we stored before.

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

回答by Ivo

A clean and elegant hover check:

干净优雅的悬停检查:

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

回答by tal

WARNING: is(':hover')is deprecated in jquery 1.8+. See this postfor a solution.

警告:is(':hover')在 jquery 1.8+ 中已弃用。请参阅此帖子以获取解决方案。

You can also use this answer : https://stackoverflow.com/a/6035278/8843to test if the mouse is hover an element :

您还可以使用此答案:https: //stackoverflow.com/a/6035278/8843来测试鼠标是否悬停在元素上:

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

回答by SLaks

You can use jQuery's hoverevent to keep track manually:

您可以使用 jQuery 的hover事件来手动跟踪:

$(...).hover(
    function() { $.data(this, 'hover', true); },
    function() { $.data(this, 'hover', false); }
).data('hover', false);

if ($(something).data('hover'))
    //Hovered!

回答by Ivan Castellanos

I needed something exactly as this (in a little more complex environment and the solution with a lot of 'mouseenters' and 'mouseleaves' wasnt working properly) so i created a little jquery plugin that adds the method ismouseover. It has worked pretty well so far.

我需要一些与此完全相同的东西(在更复杂的环境中,并且具有大量“鼠标输入”和“鼠标离开”的解决方案无法正常工作),因此我创建了一个小 jquery 插件,该插件添加了 ismouseover 方法。到目前为止,它运作良好。

//jQuery ismouseover  method
(function($){ 
    $.mlp = {x:0,y:0}; // Mouse Last Position
    function documentHandler(){
        var $current = this === document ? $(this) : $(this).contents();
        $current.mousemove(function(e){jQuery.mlp = {x:e.pageX,y:e.pageY}});
        $current.find("iframe").load(documentHandler);
    }
    $(documentHandler);
    $.fn.ismouseover = function(overThis) {  
        var result = false;
        this.eq(0).each(function() {  
                var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this);
                var offset = $current.offset();             
                result =    offset.left<=$.mlp.x && offset.left + $current.outerWidth() > $.mlp.x &&
                            offset.top<=$.mlp.y && offset.top + $current.outerHeight() > $.mlp.y;
        });  
        return result;
    };  
})(jQuery);

Then in any place of the document yo call it like this and it returns true or false:

然后在文档的任何地方你这样称呼它,它返回真或假:

$("#player").ismouseover()

I tested it on IE7+, Chrome 1+ and Firefox 4 and is working properly.

我在 IE7+、Chrome 1+ 和 Firefox 4 上对其进行了测试,并且运行正常。

回答by towr

In jQuery you can use .is(':hover'), so

在 jQuery 中你可以使用 .is(':hover'),所以

function IsMouseOver(oi)
{
   return $(oi).is(':hover');
}

would now be the most concise way to provide the function requested in the OP.

现在将是提供 OP 中请求的功能的最简洁的方法。

Note: The above does not work in IE8 or lower

注意:以上在 IE8 或更低版本中不起作用

As less succinct alternative that does work in IE8 (if I can trust IE9's IE8 modus), and does so without triggering $(...).hover(...)all over the place, nor requires knowing a selector for the element (in which case Ivo's answer is easier):

作为在 IE8 中工作的不那么简洁的替代方案(如果我可以信任 IE9 的 IE8 模式),并且不需要$(...).hover(...)到处触发,也不需要知道元素的选择器(在这种情况下,Ivo 的答案更容易):

function IsMouseOver(oi)
{
    return oi.length && 
           oi.parent()
             .find(':hover')
             .filter(function(s){return oi[0]==this})
             .length > 0;
}

回答by ripper234

I took SLaks' idea and wrapped it in a small class.

我接受了 SLaks 的想法并将其包装在一个小班级中

function HoverWatcher(selector){
  this.hovering = false;
  var self = this; 

  this.isHoveringOver = function() { 
    return self.hovering; 
  } 

    $(selector).hover(function() { 
      self.hovering = true; 
    }, function() { 
      self.hovering = false; 
    }) 
} 

var box1Watcher = new HoverWatcher('#box1');
var box2Watcher = new HoverWatcher('#box2');



$('#container').click(function() {
  alert("box1.hover = " + box1Watcher.isHoveringOver() +
        ", box2.hover = " + box2Watcher.isHoveringOver());
});

回答by SpYk3HH

JUST FYI for future finders of this.

仅供未来发现者使用。

I made a jQuery plugin that can do this and a lot more. In my plugin, to get all elements the cursor is currently hovered over, simply do the following:

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

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

As I mentioned, it also has alot of other uses as you can see in the

正如我所提到的,它还有很多其他用途,正如您在

jsFiddle found here

jsFiddle 在这里找到

回答by Phenix

As I cannot comment, so I will write this as an answer!

由于我无法发表评论,所以我会写这个作为答案!

Please understand the difference between css selector ":hover" and the hover event!

请理解css选择器":hover"和hover事件的区别!

":hover" is a css selector and was indeed removed with the event when used like this $("#elementId").is(":hover"), but in it's meaning it has really nothing to do with the jQuery event hover.

":hover" 是一个 css 选择器,当像这样使用时确实被事件删除了$("#elementId").is(":hover"),但这意味着它与 jQuery 事件悬停实际上无关。

if you code $("#elementId:hover"), the element will only be selected when you hover with the mouse. the above statement will work with all jQuery versions as your selecting this element with pure and legit css selection.

如果您编写代码$("#elementId:hover"),则只有在您用鼠标悬停时才会选择该元素。上面的语句将适用于所有 jQuery 版本,因为您使用纯合法的 css 选择来选择此元素。

On the other hand the event hover which is

另一方面,事件悬停是

$("#elementId").hover(
     function() { 
         doSomething(); 
     }
); 

is indeed deprecaded as jQuery 1.8 here the state from jQuery website:

确实被弃用为 jQuery 1.8 此处来自 jQuery 网站的状态:

When the event name "hover" is used, the event subsystem converts it to "mouseenter mouseleave" in the event string. This is annoying for several reasons:

Semantics: Hovering is not the same as the mouse entering and leaving an element, it implies some amount of deceleration or delay before firing. Event name: The event.type returned by the attached handler is not hover, but either mouseenter or mouseleave. No other event does this. Co-opting the "hover" name: It is not possible to attach an event with the name "hover" and fire it using .trigger("hover"). The docs already call this name "strongly discouraged for new code", I'd like to deprecate it officially for 1.8 and eventually remove it.

当使用事件名称“hover”时,事件子系统将其转换为事件字符串中的“mouseenter mouseleave”。这很烦人,原因有几个:

语义:悬停与鼠标进入和离开元素不同,它意味着在触发之前一定程度的减速或延迟。事件名称:附加处理程序返回的 event.type 不是悬停,而是 mouseenter 或 mouseleave。没有其他事件会这样做。选择“悬停”名称:无法附加名称为“悬停”的事件并使用 .trigger(“hover”) 触发它。文档已经将这个名称称为“强烈反对新代码”,我想正式弃用 1.8 并最终将其删除。

Why they removed the usage is(":hover") is unclear but oh well, you can still use it like above and here is a little hack to still use it.

为什么他们删除了使用 is(":hover") 尚不清楚,但是哦,你仍然可以像上面一样使用它,这里有一个小技巧仍然可以使用它。

(function ($) {
   /** 
    * :hover selector was removed from jQuery 1.8+ and cannot be used with .is(":hover") 
    * but using it in this way it works as :hover is css selector! 
    *
    **/
    $.fn.isMouseOver = function() {
        return $(this).parent().find($(this).selector + ":hover").length > 0;
    };
})(jQuery);

Oh and I would not recommentthe timeout version as this brings a lot of complexity, use timeout functionalities for this kind of stuff if there is no other way and believe me, in 95% percent of all cases there is another way!

哦,我不会推荐超时版本,因为这会带来很多复杂性,如果没有其他方法,请对此类内容使用超时功能,相信我,在95% 的情况下,还有另一种方法

Hope I could help a couple people out there.

希望我可以帮助那里的几个人。

Greetz Andy

格雷茨安迪