在 html 页面上实现拖放行为时,通常需要这种类型的行为。下面的解决方案在 IE8.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);
}
}
然后使用此方法将事件处理程序附加到文档对象 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");
}
});
最后,这是一个 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>
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');
}
});
<script>
var leave = 0
//show modal when mouse off of page
$("html").mouseleave(function() {
//check for first time
if (leave < 1) {
modal.style.display = "block";
leave = leave + 1;
}
});
// Get the modal with id="id01"
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
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
document.addEventListener("mouseout", function(e) {
let t = e.relatedTarget || e.toElement;
if (!t || t.nodeName == "HTML") {
console.log("left window");
}
});
document.write("<br><br>PROBLEM<br><br><div>Mouseout trigg on HTML elements</div>")
var x = 0
document.addEventListener("mouseleave", function(e) { console.log(x++)
})
document.write("<br><br>SOLUTION<br><br><div>Mouseleave do not trigg on HTML elements</div>")
您可以在任何 HTML 元素上设置事件。但是在 document.body上不要有事件,因为当鼠标指针在滚动条上时,当你想要滚动但不想触发鼠标离开事件时,窗口滚动条可能会收缩正文并触发。改为在 document上设置它,如示例所示。