如何使用JQuery检查光标是否hover在元素上

可以检查光标是否hover在元素上。

就像是

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

注意:我只想检查未设置事件。

 .is(':hover'); 

要么

 $('#divId:hover'); 

更新的答案!

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

测试它是否hover……

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

你可以使用jQuery的hover()mouseenter()mouseover()

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

这将触发mouseenter和mouseleave。 您可以为每个事件添加单独的事件处理程序。

因此,如果您想要执行类似操作, if hovering over #divId increase x by one, and when you stop hovering decrease y by oneif hovering over #divId increase x by one, and when you stop hovering decrease y by one

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

如果你真的想要一个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) { ... 

尝试使用这个jsFiddle

例如:

 $(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."); }); }); 

你可以使用.hover() 。 它可以像这样使用:

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

从文档中使用它的一个例子是:

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

根据您的操作, mouseover()http://api.jquery.com/mouseover/ )或hover()http://api.jquery.com/hover/ )可能很有用。