开发者

jQuery mouse in div

开发者 https://www.devze.com 2023-02-06 05:58 出处:网络
I\'ve been googling and looking on Stackoverflow but I can\'t find the answer. Is there an easy way to 开发者_Go百科know if a mouse is in a div, or not (hovering)?

I've been googling and looking on Stackoverflow but I can't find the answer.

Is there an easy way to 开发者_Go百科know if a mouse is in a div, or not (hovering)?

The only solution I could come up with is:

$("#somediv").hover(
  function() {
    $(this).data("in", true);
  },
  function() {
    $(this).removeData("in");
});

and then to check:

if ($("#somediv").data("in")) {
   ...
}

Is there really no easier way?


You can track the mouse's position:

$(document).mousemove(function(e){
  x = e.pageX; // globals, but you could tie them to a namespace or whatever
  y = e.pageY;
}); 

The advantage here is that you needn't worry about binding/unbinding a whole bunch of hover events for a whole lot of different elements. You can then ask (at any given time, as opposed to my second solution) whether or not the mouse position falls within any element's coordinates.

You might prefer to bind it not in an anonymous function so that you can unbind it (for performance reasons and the like).

One drawback with this approach is that mousemove() only fires when you move the mouse although if i scroll with the keyboard the mouse position in the document has changed without the event firing. This does not apply to your solution (at least not with my primitive jsFiddle test in FF). You can fix this by updating the coords with a keypress event, or something similar, although that makes things complicated, and you want simple.

Alternatively, you can use the event object given to events and ask the mouse's position directly from your relevant event. So lets say you only needed to check whether or not the mouse was in a given div when a simple event happened, say the user triggered a mouseup() somewhere, then you just refer to the event object you have:

someDiv.mouseup(function(e){

  // ...
  // other stuff
  // ...

  if (ns.isMouseInDiv(someOtherDiv, e))
     foo();

});

Again, you save having to bind to every object you want to check.


Can't you just set a var onmouseover, and unset it onmouseout?


In the hover-out event handler of the icon then, you could perhaps check whether the dialog div has the :hover pseudo class. Like:

if($("#dialog:hover").length)){
    ...
}

Haven't tried it though... Did I at least get what you're trying to do? ;)

UPDATE: try it here: http://jsfiddle.net/cpak/MBJ6Q/

As mentioned in comment below, requires mouse to go directly from the icon to the dialog.

0

精彩评论

暂无评论...
验证码 换一张
取 消