var timer;
var stoppedElement=document.getElementById("stopped"); // store element for faster access
function mouseStopped(){ // the actual function that is called
stoppedElement.innerHTML="Mouse stopped";
}
window.addEventListener("mousemove",function(){
stoppedElement.innerHTML="Mouse moving";
clearTimeout(timer);
timer=setTimeout(mouseStopped,300);
});
这个小提琴检测到鼠标移动但是当移动鼠标滚轮时它表示鼠标正在移动,我们可以将移动和滚轮事件分开吗?
答案 0 :(得分:1)
除滚动事件外,Webkit浏览器还会触发mousemove事件,因为滚动后光标可能处于不同的位置。
解决方案是手动检查位置是否改变:
var timer;
var stoppedElement=document.getElementById("stopped"); // store element for faster access
function mouseStopped(){ // the actual function that is called
stoppedElement.innerHTML="Mouse stopped";
}
window.addEventListener("mousemove",function(e){
if ((window.lastX !== e.clientX && window.lastX !== undefined)
|| (window.lastY !== e.clientY && window.lastY !== undefined)) {
stoppedElement.innerHTML="Mouse moving";
clearTimeout(timer);
timer=setTimeout(mouseStopped,300);
}
window.lastX = e.clientX
window.lastY = e.clientY
})

<div id="stopped"></div>
&#13;