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

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

    I couldn't use any of the suggestions above.
    Why I prefer my solution?
    This method checks if mouse is over an element at any time chosen by You.
    Mouseenter and :hover are cool, but mouseenter triggers only if you move the mouse, not when element moves under the mouse.
    :hover is pretty sweet but ... IE

    So I do this:

    No 1. store mouse x, y position every time it's moved when you need to,
    No 2. check if mouse is over any of elements that match the query do stuff ... like trigger a mouseenter event

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

提交回复
热议问题