当鼠标离开视口时如何使JQuery .hover()工作?

时间:2022-11-04 17:41:44

The below code will put a div at the very top of the view port.

下面的代码将div放在视图端口的最顶部。

The expected behavior is:

预期的行为是:

When the user mouses over the div, then moves the mouse up until the cursor is out of the viewport, a message of "hover out" should be logged in the console. The issue is that nothing gets logged to the console.

当用户将鼠标悬停在div上时,然后向上移动鼠标直到光标离开视口,应在控制台中记录“悬停”消息。问题是没有任何内容记录到控制台。

How can I make JQuery .hover() log something to the console when the mouse leaves viewport?

当鼠标离开视口时,如何让JQuery .hover()将某些内容记录到控制台?

<body style="margin: 0; padding: 0;">
  <div class="foo" style="background-color: blue; width: 100px; height: 100px;">
    Test
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

  <script>

    $(".foo").hover(function(){
        console.log("hover in");
    }, function(){
        console.log("hover out");
    });

   </script>

2 个解决方案

#1


8  

Using mouseover and mouseout instead of hover seems to fix it.

使用鼠标悬停和鼠标悬停而不是悬停似乎解决了它。

$(".foo").mouseover(function(){
    console.log("hover in");
});

$(".foo").mouseout(function(){
    console.log("hover out");
});

See it in action here.

在这里看到它。

Note that even this won't work if there is no chrome around the browser window. For example, when I maximize FF4 or put it into full screen mode, the edge of the browser window is flush with the edge of my screen so there is nowhere for the cursor to go to the left of the div in that case so the mouseout event will never fire.

请注意,如果浏览器窗口周围没有镶边,即使这样也行不通。例如,当我最大化FF4或将其置于全屏模式时,浏览器窗口的边缘与我的屏幕边缘齐平,因此在这种情况下光标无法转到div的左侧,因此鼠标移动事件永远不会开火。

#2


3  

The solution is to change the JQuery version from 1.5.1 to 1.4.4. Not a good solution, but it works.

解决方案是将JQuery版本从1.5.1更改为1.4.4。不是一个好的解决方案,但它确实有效。

#1


8  

Using mouseover and mouseout instead of hover seems to fix it.

使用鼠标悬停和鼠标悬停而不是悬停似乎解决了它。

$(".foo").mouseover(function(){
    console.log("hover in");
});

$(".foo").mouseout(function(){
    console.log("hover out");
});

See it in action here.

在这里看到它。

Note that even this won't work if there is no chrome around the browser window. For example, when I maximize FF4 or put it into full screen mode, the edge of the browser window is flush with the edge of my screen so there is nowhere for the cursor to go to the left of the div in that case so the mouseout event will never fire.

请注意,如果浏览器窗口周围没有镶边,即使这样也行不通。例如,当我最大化FF4或将其置于全屏模式时,浏览器窗口的边缘与我的屏幕边缘齐平,因此在这种情况下光标无法转到div的左侧,因此鼠标移动事件永远不会开火。

#2


3  

The solution is to change the JQuery version from 1.5.1 to 1.4.4. Not a good solution, but it works.

解决方案是将JQuery版本从1.5.1更改为1.4.4。不是一个好的解决方案,但它确实有效。