当鼠标离开视口时如何使 JQuery .hover() 工作?
下面的代码将在视口的最顶部放置一个 div。
预期的行为是:
当用户将鼠标悬停在 div 上,然后向上移动鼠标直到光标移出视口时,应在控制台中记录一条“悬停”消息。问题是控制台没有记录任何内容。
当鼠标离开视口时,如何使 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>
The below code will put a div at the very top of the view port.
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.
How can I make JQuery .hover() log something to the console when the mouse leaves viewport?
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
mouseover
和mouseout
而不是hover
似乎可以解决此问题。在此处查看实际操作。
请注意,如果没有浏览器窗口周围的镶边。例如,当我最大化 FF4 或将其置于全屏模式时,浏览器窗口的边缘与屏幕边缘齐平,因此在这种情况下光标无处可移至 div 的左侧,因此鼠标移出事件永远不会触发。
Using
mouseover
andmouseout
instead ofhover
seems to fix it.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.
解决方案是将JQuery版本从1.5.1更改为1.4.4。这不是一个好的解决方案,但它确实有效。
The solution is to change the JQuery version from 1.5.1 to 1.4.4. Not a good solution, but it works.