如何检测鼠标何时离开窗口?

88 javascript browser mouse

我希望能够检测到鼠标何时离开窗口,以便在用户的鼠标位于其他位置时可以阻止事件触发.

有关如何做到这一点的任何想法?

J M*_*lls 94

在html页面上实现拖放行为时,通常需要这种类型的行为.以下解决方案在MS Windows XP计算机上的IE 8.0.6,FireFox 3.6.6,Opera 10.53和Safari 4上进行了测试.
首先是Peter-Paul Koch的一个小功能; 跨浏览器事件处理程序

function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用此方法将事件处理程序附加到文档对象mouseout事件:

addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;
    if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        // for now we can just use an alert
        alert("left window");
    }
});
Run Code Online (Sandbox Code Playgroud)

最后,这是一个html页面,其中嵌入了用于调试的脚本:

<html>
<head>
<script type="text/javascript">
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}
addEvent(window,"load",function(e) {
    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            // stop your drag event here
            // for now we can just use an alert
            alert("left window");
        }
    });
});
</script>
</head>
<body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 如果其他HTML元素填充窗口,则不起作用. (3认同)

Man*_*jua 41

如果你正在使用jQuery那么这个简短而又甜蜜的代码怎么样 -

$(document).mouseleave(function () {
    console.log('out');
});
Run Code Online (Sandbox Code Playgroud)

只要鼠标不在您的页面中,就会触发此事件.只需更改功能即可执行任何操作.

你也可以使用:

$(document).mouseenter(function () {
    console.log('in');
});
Run Code Online (Sandbox Code Playgroud)

当鼠标再次返回页面时触发.

资料来源:https://stackoverflow.com/a/16029966/895724


小智 24

这对我有用:

addEvent(document, 'mouseout', function(evt) {
  if (evt.toElement == null && evt.relatedTarget == null) {
    alert("left window");
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 什么是`addEvent`? (7认同)
  • 它是[Joshua Mills答案]中定义的函数(http://stackoverflow.com/a/3187524/540776) (5认同)
  • 在ie8上,undefinedTarget未定义,在ie9 +和firefox上,toElement未定义。因为这样,正确的评估是:if(((evt.relatedTarget === null)||(evt.toElement === null)){ (3认同)
  • 谓词可以更简洁,如`if (!evt.toElement &amp;&amp; !evt.relatedTarget)` (2认同)

dip*_*pas 21

这是 2021 年的答案:

可以在标签中使用mouseleave(并mouseenter在输入时进行检测)html(在 Chrome 91 和 Firefox 90 中测试)

通过将鼠标悬停在下面的代码片段中来尝试。

document.documentElement.addEventListener('mouseleave', () => console.log('out'))
document.documentElement.addEventListener('mouseenter', () => console.log('in'))
Run Code Online (Sandbox Code Playgroud)


Dap*_*que 15

为了检测mouseleave而不考虑滚动条和autcomplete字段或检查:

document.addEventListener("mouseleave", function(event){

  if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
  {

     console.log("I'm out");

  }
});
Run Code Online (Sandbox Code Playgroud)

条件说明:

event.clientY <= 0  is when the mouse leave from the top
event.clientX <= 0  is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom
Run Code Online (Sandbox Code Playgroud)


Jay*_*wal 6

也许这会对后来来这里的一些人有所帮助。 window.onblurdocument.mouseout

window.onblur在以下情况下触发:

  • Ctrl+Tab您可以使用或切换到另一个窗口Cmd+Tab
  • 您将注意力集中(不仅仅是将鼠标悬停在文档检查器上)。
  • 你切换桌面。

基本上只要浏览器选项卡失去焦点。

window.onblur = function(){
    console.log("Focus Out!")
}
Run Code Online (Sandbox Code Playgroud)

document.mouseout在以下情况下触发:

  • 您将光标移动到标题栏上。
  • Ctrl+Tab您可以使用或切换到另一个窗口Cmd+Tab
  • 您打开将光标移至文档检查器。

基本上在任何情况下,当您的光标离开文档时。

document.onmouseleave = function(){
    console.log("Mouse Out!")
}
Run Code Online (Sandbox Code Playgroud)


Emm*_*uel 5

这些答案都不适合我.我现在正在使用:

document.addEventListener('dragleave', function(e){

    var top = e.pageY;
    var right = document.body.clientWidth - e.pageX;
    var bottom = document.body.clientHeight - e.pageY;
    var left = e.pageX;

    if(top < 10 || right < 20 || bottom < 10 || left < 10){
        console.log('Mouse has moved out of window');
    }

});
Run Code Online (Sandbox Code Playgroud)

我正在使用它来拖放文件上传小部件.当鼠标距离窗口边缘一定距离时触发它并不是绝对准确的.


Cla*_*diu 5

我已经尝试了以上所有方法,但似乎没有预期的效果。一个小小的研究后,我发现,e.relatedTargetHTML只是鼠标退出窗口前

所以...我最终得到了这个:


document.body.addEventListener('mouseout', function(e) {
    if (e.relatedTarget === document.querySelector('html')) {
        console.log('We\'re OUT !');
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您发现任何问题或改进,请告诉我!

2019更新

(因为user1084282被发现)

document.body.addEventListener('mouseout', function(e) {
    if (!e.relatedTarget && !e.toElement) {
        console.log('We\'re OUT !');
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 在Chrome上无法为我工作。当鼠标离开窗口时,“ relatedTarget”为null。受@ user1084282答案的启发,将其更改为:`if(!e.relatedTarget &amp;&amp;!e.toElement){...}`,并且可以正常工作 (2认同)

Sam*_*rif 5

使用onMouseLeave事件可防止冒泡,并允许您轻松检测鼠标何时离开浏览器窗口。

<html onmouseleave="alert('You left!')"></html>
Run Code Online (Sandbox Code Playgroud)

http://www.w3schools.com/jsref/event_onmouseleave.asp


End*_*der 0

您可以对 body 标记执行 OnMouseOut 函数调用。