我目前通过使用以下内容每 1 秒将鼠标移动坐标保存到一个 JSON 文件:
window.onload = function() {
setInterval(track, 1000);
}
track是通过ajax将坐标保存到json文件的函数。
但是,当鼠标不在浏览器上时使用此方法,该函数仍然每秒刷新一次,因此会采用 event.clientX/Y 中最后保存的坐标。
我知道 onmouseenter 和 onmouseout 函数,但是我没有成功地实现它们来达到我的目的。我测试过的功能如下:
document.onmouseenter = function(i){
console.log('IN');
}
document.onmouseleave = function(l){
console.log('OUT');
}
但是,上面的 onmouseenter 函数仅在第一次单击时输出“IN”。而 onmouseleave 函数永远不会输出 'OUT'。
如有任何建议,我们将不胜感激
最佳答案
保存后取消设置 x/y,然后在尝试保存时检查它们是否已设置怎么样?
var x, y; // store mouse coords
window.addEventListener('mousemove', function(e) {
x = e.clientX;
y = e.clientY;
});
setInterval(function() {
if (x !== undefined && y !== undefined) { // check if they're set
// save your locations, only called when mouse is moved on page
x = y = undefined; // unset them
}
}, 1000);
关于javascript - 当鼠标离开浏览器时停止保存到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41315620/