开发者

How can I check if the cursor is hovering on an element using JQuery

It possible to check if the cursor is hovering on an element.

Something开发者_开发问答 like

 $("#divId").is("hover");

NOTE: I just want to check not set event.


.is(':hover');

or

$('#divId:hover');


Updated answer!

$("#foo").hover(function() {
    $(this).data("hovered", true);
}, function() {
    $(this).data("hovered", false);
}); 

Testing if it is hovered...

if ( $("#foo").data("hovered") ) {
    // it is hovered
} else {
    // it's not hovered
}


You can use jQuery's hover(), mouseenter() or mouseover()

$("#divId").hover(function() { alert("hovering"; });

This will fire on mouseenter and mouseleave. You can add separate event handlers for each.

So if you want to do something like, if hovering over #divId increase x by one, and when you stop hovering decrease y by one:

$("#divId").hover(function() { ++x; }, 
                  function() { --y; });

If you really want an if hovering:

var hovering = 0;
$("#divId").hover(function() { hovering = 1; },
                  function() { hovering = 0; });
...
// Then inside somewhere useful. Maybe in a setInterval, or triggered by
//    another action...
if (hovering) { ...

Try it out with this jsFiddle

For example:

$(function() {
    var hovering = 0;
    $("div").hover(function() { hovering = 1; },
                   function() { hovering = 0; });

    $(document).keyup(function() {
         if (hovering) alert("hovering!");     // This is the "if hovering"
         else          alert("not hovering.");
    });
});


You can use .hover(). It's can be used like so:

$("selector").hover(
    function (){
        //mouse over
    },
    function (){
       //mouse out
    }
);

An example of it's use from the documentation is here:

$("li").hover(
  function () {
    $(this).append($("<span> ***</span>"));
  }, 
  function () {
    $(this).find("span:last").remove();
  }
);


Depending on what you are doing either mouseover() (http://api.jquery.com/mouseover/) or hover() (http://api.jquery.com/hover/) can be useful.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜