javascript - 无法理解为什么事件未定义
问题描述
对不起,我觉得这是一个非常经典的问题,但由于我正在学习,我不知道为什么它在我的情况下不起作用。
我正在尝试使用一个脚本来检测您的空闲时间,如果是这样,请执行一个获取鼠标位置的函数。为了做到这一点,我有一个TimerIncrement()
可以检查 2 秒不活动的函数,如果是这样,我想执行另一个调用函数GetMousePos
来获取鼠标位置并拥有它的 console.log。
我试过在网上和论坛上寻找,但我所做的一切都没有帮助。感谢您的宝贵帮助。
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1s
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 2sec
getMousePos();
idleTime = 0; // reset timer
}
}
function getMousePos(event) {
x = event.pageX;
y = event.pageY;
console.log(x);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
解决方案
因此,您调用getMousePos
的参数是 event 并且您没有向其传递任何内容,因此无法将属性“pageX”作为 event.pageX 读取(未定义事件)。您只能在事件回调上访问事件对象,所以我假设您想要获取您看到的最后一个事件(如果有的话)。
下面应该对你有用,存储你看到的最后一个事件,然后你应该能够获得你想要的信息。希望此代码示例能让您了解所缺少的内容。
var idleTime = 0;
var lastEvent = undefined;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1s
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
lastEvent = e;
});
$(this).keypress(function (e) {
idleTime = 0;
lastEvent = e;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 2sec
getMousePos(lastEvent);
idleTime = 0; // reset timer
}
}
function getMousePos(event) {
if (!event) {
console.log("No mouse or keypress has been executed yet");
return;
}
x = event.pageX;
y = event.pageY;
console.log(x);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>