js实现鼠标滚动
监听鼠标滚动事件
使用 addEventListener 监听 wheel 事件,可以获取鼠标滚轮的滚动方向和速度。以下是一个基本示例:
window.addEventListener('wheel', function(event) {
console.log('Delta Y:', event.deltaY); // 垂直滚动量
console.log('Delta X:', event.deltaX); // 水平滚动量
});
deltaY 为正表示向下滚动,为负表示向上滚动。deltaX 类似,用于水平滚动。
自定义滚动行为
如果需要阻止默认滚动行为(如实现自定义滚动效果),可以调用 event.preventDefault():

window.addEventListener('wheel', function(event) {
event.preventDefault();
// 自定义滚动逻辑
const scrollSpeed = event.deltaY * 0.1; // 调整滚动速度
window.scrollBy(0, scrollSpeed);
});
平滑滚动动画
通过 requestAnimationFrame 实现平滑滚动动画:
let isScrolling = false;
window.addEventListener('wheel', function(event) {
event.preventDefault();
if (isScrolling) return;
isScrolling = true;
const targetScrollY = window.scrollY + event.deltaY;
smoothScroll(targetScrollY);
});
function smoothScroll(targetY) {
const currentY = window.scrollY;
const distance = targetY - currentY;
const duration = 500; // 动画持续时间(毫秒)
let startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
const progressRatio = Math.min(progress / duration, 1);
const easing = progressRatio < 0.5
? 2 * progressRatio * progressRatio
: 1 - Math.pow(-2 * progressRatio + 2, 2) / 2; // 缓动函数
window.scrollTo(0, currentY + distance * easing);
if (progress < duration) {
requestAnimationFrame(step);
} else {
isScrolling = false;
}
}
requestAnimationFrame(step);
}
横向滚动控制
监听 deltaX 实现横向滚动:

const scrollContainer = document.getElementById('horizontal-scroll');
scrollContainer.addEventListener('wheel', function(event) {
event.preventDefault();
scrollContainer.scrollLeft += event.deltaY; // 用 deltaY 控制横向滚动
});
兼容性处理
对于旧版浏览器(如 IE),可以使用 mousewheel 事件替代 wheel,并通过 wheelDelta 获取滚动量:
window.addEventListener('mousewheel', function(event) {
const delta = event.wheelDelta;
console.log('Wheel Delta:', delta); // 正值向上,负值向下
});
滚动节流优化
避免滚动事件频繁触发导致性能问题,使用节流函数(throttle)优化:
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('wheel', throttle(function(event) {
console.log('Throttled scroll:', event.deltaY);
}, 100)); // 每100毫秒触发一次
滚动方向检测
通过比较前后滚动事件的位置判断方向:
let lastScrollY = window.scrollY;
window.addEventListener('scroll', function() {
const currentScrollY = window.scrollY;
const direction = currentScrollY > lastScrollY ? 'down' : 'up';
lastScrollY = currentScrollY;
console.log('Scroll direction:', direction);
});






