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

前端 未结 24 2098
不思量自难忘°
不思量自难忘° 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:01

    I see timeouts used for this a lot, but in the context of an event, can't you look at coordinates, like this?:

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

    Depending on context, you may need to make sure (this==e.target) before calling areXYInside(e).

    fyi- I'm looking at using this approach inside a dragLeave handler, in order to confirm that the dragLeave event wasn't triggered by going into a child element. If you don't somehow check that you're still inside the parent element, you might mistakenly take action that's meant only for when you truly leave the parent.

    EDIT: this is a nice idea, but does not work consistently enough. Perhaps with some small tweaks.

    0 讨论(0)
  • 2020-11-22 09:04

    Thanks to both of you. At some point I had to give up on trying to detect if the mouse was still over the element. I know it's possible, but may require too much code to accomplish.

    It took me a little while but I took both of your suggestions and came up with something that would work for me.

    Here's a simplified (but functional) example:

    $("[HoverHelp]").hover (
        function () {
            var HelpID = "#" + $(this).attr("HoverHelp");
            $(HelpID).css("top", $(this).position().top + 25);
            $(HelpID).css("left", $(this).position().left);
            $(HelpID).attr("fadeout", "false");
            $(HelpID).fadeIn();
        },
        function () {
            var HelpID = "#" + $(this).attr("HoverHelp");
            $(HelpID).attr("fadeout", "true");
            setTimeout(function() { if ($(HelpID).attr("fadeout") == "true") $(HelpID).fadeOut(); }, 100);
        }
    );
    

    And then to make this work on some text this is all I have to do:

    <div id="tip_TextHelp" style="display: none;">This help text will show up on a mouseover, and fade away 100 milliseconds after a mouseout.</div>
    
    This is a <span class="Help" HoverHelp="tip_TextHelp">mouse over</span> effect.
    

    Along with a lot of fancy CSS, this allows some very nice mouseover help tooltips. By the way, I needed the delay in the mouseout because of tiny gaps between checkboxes and text that was causing the help to flash as you move the mouse across. But this works like a charm. I also did something similar for the focus/blur events.

    0 讨论(0)
  • 2020-11-22 09:04
    $(document).hover(function(e) {
        alert(e.type === 'mouseenter' ? 'enter' : 'leave');
    });
    

    FIDDLE

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:05

    Just a note about the popular and helpful Arthur Goldsmith answer above: If you're moving your mouse from one element to another in IE (at least until IE 9) you may have some trouble getting this to work correctly if the new element has a transparent background (which it would by default). My workaround was the give the new element a transparent background image.

    0 讨论(0)
  • 2020-11-22 09:07

    This code illustrates what happytime harry and 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.

    $("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); 
    });
    
    0 讨论(0)
提交回复
热议问题