Skip to content

鼠标移动速度侦测 ​

本节目标:理解“鼠标移动速度侦测”的核心思路,并能把它用于实际开发或面试表达。 mousemove: 浏览器有最小的监听和反映时间,同样的距离,操作快(用的时间短),浏览器能够反映过来的次数就少,触发mousemove这个行为的次数也变少了。

水平方向的运动只跟即将松开手一瞬间运动的速度有关系:我们需要获取即将松开一瞬间的速度。

<head>
<meta charset="utf-8">
<style>
.wrapper {
margin: 100px auto;
width: 1000px;
text-align: center;
padding: 0;
background: gray;
}
@keyframes rotate {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="wrapper">
<img id="logo" src="rocket.png" alt="rocket" />
</div>
<script>
let logo = document.getElementById('logo');
document.body.addEventListener('mousemove', rotate, false);
let x = 0;
let speed = 0;
function rotate(e) {
if (x === 0 ) {
logo.style.animation = `rotate 2s infinite linear`;
x = e.pageX;
} else {
speed = 10 / Math.abs(e.pageX - x);
console.log(speed);
logo.style.animation = `rotate ${speed}s infinite linear`;
x = e.pageX;
}
}
</script>
</body>

本站总访问 — 次