鼠标事件延迟是指当用户移动或点击鼠标时,浏览器响应这些动作的时间比预期要长。在JavaScript中,鼠标事件如mousemove
、click
、mousedown
等可能会因为各种原因导致延迟响应。
mousemove
在快速移动时会触发大量事件function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}
// 使用示例
window.addEventListener('mousemove', throttle(function(e) {
console.log('Mouse position:', e.clientX, e.clientY);
}, 100)); // 每100ms最多执行一次
function debounce(func, delay) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
// 使用示例
window.addEventListener('mousemove', debounce(function(e) {
console.log('Mouse stopped moving:', e.clientX, e.clientY);
}, 250));
let ticking = false;
window.addEventListener('mousemove', function(e) {
if (!ticking) {
window.requestAnimationFrame(function() {
// 在这里执行你的处理逻辑
console.log('Optimized mouse position:', e.clientX, e.clientY);
ticking = false;
});
ticking = true;
}
});
window.addEventListener('mousemove', function(e) {
console.log('Mouse position:', e.clientX, e.clientY);
}, { passive: true }); // 告诉浏览器不会调用preventDefault()
// 不好的做法 - 每次mousemove都修改DOM
window.addEventListener('mousemove', function(e) {
document.getElementById('position').textContent = `X: ${e.clientX}, Y: ${e.clientY}`;
});
// 更好的做法 - 使用requestAnimationFrame批量更新
let lastX, lastY;
let needsUpdate = false;
window.addEventListener('mousemove', function(e) {
lastX = e.clientX;
lastY = e.clientY;
if (!needsUpdate) {
needsUpdate = true;
requestAnimationFrame(updatePosition);
}
});
function updatePosition() {
document.getElementById('position').textContent = `X: ${lastX}, Y: ${lastY}`;
needsUpdate = false;
}
通过以上方法,可以显著减少Vanilla JavaScript中鼠标事件的延迟问题,提高用户体验。
没有搜到相关的文章