需求描述
监听用户是否有操作,如果一定时间内无操作则给予提示或行为
使用到的API
keydown:监听键盘事件touchstart:监听触摸屏幕事件
示例代码
touchTime,记录最近一次触发操作的时间,checkTimer为计时器。
data() {
return {
touchTime: '', // 最近一次触发操作的时间
checkTimer: 0, // 监听操作的计时器
}
}
监听用户是否触发了操作,触发操作时则更新touchTime。通过计时器checkTimer,比较当前时间点与最近一次触发操作的时间touchTime的时间差。超过指定的时间则给予提示等行为。
mounted() {
// 监听用户是否触发了键盘事件,或者触摸了屏幕
document.addEventListener("keydown", this.updateTouchTime); // 监听键盘
document.addEventListener('touchstart', this.updateTouchTime); // 监听触摸屏幕
this.monitorHandle()
}
methods: {
// 触发操作时更新touchTime
updateTouchTime() {
this.touchTime = new Date().getTime();
},
// 一定时间内无操作给予提示等行为,假设无操作30秒后提示
monitorHandle() {
this.checkTimer = setInterval(() => {
let nowtime = new Date().getTime();
if (nowtime - this.touchTime > 30 * 1000) {
// 提示用户已经30秒无操作了
// 清除计时器
clearInterval(this.checkTimer);
}
}, 1000)
}
}