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

前端 未结 24 2118
不思量自难忘°
不思量自难忘° 2020-11-22 08:10

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

I don\'t want to use the mouseover event because I\'m already using it for something else. I

24条回答
  •  长情又很酷
    2020-11-22 09:05

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

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

    ":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.

    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.

    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:

    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.

    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.

    (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 recomment the 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!

    Hope I could help a couple people out there.

    Greetz Andy

提交回复
热议问题