如何检测鼠标何时离开窗口? [英] How can I detect when the mouse leaves the window?

查看:28
本文介绍了如何检测鼠标何时离开窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检测到鼠标何时离开窗口,以便在用户的鼠标在别处时停止触发事件.

I want to be able to detect when the mouse leaves the window so I can stop events from firing while the user's mouse is elsewhere.

对如何做到这一点有任何想法吗?

Any ideas of how to do this?

推荐答案

请记住,我的回答已经过时了.

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

Please keep in mind that my answer has aged a lot.

This type of behavior is usually desired while implementing drag-drop behavior on an html page. The solution below was tested on IE 8.0.6, FireFox 3.6.6, Opera 10.53, and Safari 4 on an MS Windows XP machine.
First a little function from Peter-Paul Koch; cross browser event handler:

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

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

And then use this method to attach an event handler to the document objects mouseout event:

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");
    }
});

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

Finally, here is an html page with the script embedded for debugging:

<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>

这篇关于如何检测鼠标何时离开窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆