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

20

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

类似这样的代码:

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

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

5个回答

22
.is(':hover');
或者
$('#divId:hover');

5
请使用以下翻译:如果 $(selector:hover) 的长度大于零,则执行 //dostuff。 - Anthony Corbelli
从jQuery 1.6.4开始,在ie中它不起作用,并且在api.jquery.com上也没有记录。 - wheresrhys
在旧版的IE中,使用:hover作为初始选择器并不起作用。在任何浏览器中都不能使用 is(":hover") 。在撰写本文时,使用 is("hover") 在所有浏览器中都能起作用。 - BenCr

4

更新的答案!

(此处无需翻译)
$("#foo").hover(function() {
    $(this).data("hovered", true);
}, function() {
    $(this).data("hovered", false);
}); 

测试是否悬停...

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

为什么不在mouseenter时存储hover=yes,并在mouseleave时存储hover=no?这样无论悬停多长时间都可以工作。 - Peter Ajtai
@Peter,你的答案去哪了?我刚刚在测试你的解决方案,看起来是可以工作的... - Šime Vidas

3
你可以使用jQuery的 hover(), mouseenter() 或者 mouseover() 方法。
$("#divId").hover(function() { alert("hovering"; });

这将在鼠标进入和离开时触发。您可以为每个事件添加单独的事件处理程序。
因此,如果您想执行以下操作:如果悬停在#divId上,则将x增加1,并在停止悬停时将y减少1
$("#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.");
    });
});

@Mark - 好的,那是基础。我加了一个选项。 - Peter Ajtai
不,它并不是。它只是在访问者悬停时发出警报。OP需要像这样进行检查:if ( hovering? ) { do one thing; } else { do another thing; } - Šime Vidas
那似乎可以工作,但是@GetFresh的答案似乎是“终极”解决方案,因为它不需要任何hover()绑定... - Šime Vidas

2

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

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

文档中使用的一个示例如下:

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接