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

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

提交回复
热议问题