问题描述
我希望能够检测到鼠标何时离开窗口,以便在用户的鼠标在别处时停止触发事件.
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>
这篇关于如何检测鼠标何时离开窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!