如何知道鼠标是否在窗口内

How to know whether the mouse is inside the window?

本文关键字:窗口 是否 何知道 鼠标      更新时间:2023-09-26

我似乎找不到答案。

我有一个mouseleave事件,在其中我想检查,当事件触发时,鼠标是否当前在窗口内(如果不是,它可以是浏览器的选项卡栏,后退按钮等)。

    var cursorInPage = false;
$(window).on('mouseout', function() {
    cursorInPage = false;
});
$(window).on('mouseover', function() {
    cursorInPage = true;
});
$('#some_element').on("mouseleave",function(){
  if(cursorInPage === true){
     //Code here runs despite mouse not being inside window
    }
 });

我可以绑定一个窗口mouseleave事件吗?如果离开文档/窗口的外部作用域,是否会触发这样的事件?上面的代码有一个问题,因为我认为元素的mouseleave在窗口

之前触发。

我不太确定你要我们在这里写什么,但你可以简单地设置一个布尔值:

var cursorInPage = false;
$(window).on('mouseout', function() {
    cursorInPage = false;
});
$(window).on('mouseover', function() {
    cursorInPage = true;
});

然后使用布尔值继续:

if (cursorInPage === true) {
    alert('Woo, the cursor is inside the page!');
}

下面是一个JSFiddle示例,它在光标进入或离开窗口区域时改变主体背景颜色,在查看全屏结果时更好地显示。

只是测试了一下,希望能有所帮助。这里是它的jsFiddle。

$(document,window,'html').mouseleave(function(){alert('bye')}).mouseenter(function(){alert('welcome back!')})

您可以尝试:

$('body').mouseout(function() {
alert('Bazzinga...');
});

$(window).mouseleave(function() {
alert('Bazzinga...');
});

当鼠标在元素内

$('#outer').mouseover(function() {
  $('#log').append('<div>Handler for .mouseover() called.</div>');
});

当鼠标离开元素

$('#outer').mouseleave(function() {
  $('#log').append('<div>Handler for .mouseleave() called.</div>');
});