js实现滚轮
监听滚轮事件
在JavaScript中,可以通过addEventListener来监听滚轮事件。使用wheel事件可以捕获鼠标滚轮的滚动行为。
window.addEventListener('wheel', function(event) {
console.log(event.deltaY); // 输出垂直方向的滚动量
// 其他逻辑处理
});
event.deltaY表示垂直方向的滚动量,正值表示向下滚动,负值表示向上滚动。event.deltaX表示水平方向的滚动量。
阻止默认滚动行为
如果需要阻止默认的滚动行为(例如实现自定义滚动效果),可以调用event.preventDefault()。
window.addEventListener('wheel', function(event) {
event.preventDefault();
// 自定义滚动逻辑
});
平滑滚动实现
使用window.scrollTo可以实现平滑滚动效果。通过设置behavior: 'smooth'可以让滚动动画更流畅。

window.scrollTo({
top: 1000, // 滚动到指定位置
behavior: 'smooth' // 平滑滚动
});
自定义滚动动画
如果需要更复杂的滚动动画,可以使用requestAnimationFrame逐帧控制滚动位置。
function smoothScrollTo(targetY, duration = 1000) {
const startY = window.scrollY;
const distance = targetY - startY;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, startY + distance * progress);
if (progress < 1) {
requestAnimationFrame(scrollStep);
}
}
requestAnimationFrame(scrollStep);
}
// 调用示例
smoothScrollTo(1000);
检测滚动方向
通过比较当前滚动位置和上一次滚动位置,可以判断滚动方向。
let lastScrollY = window.scrollY;
window.addEventListener('scroll', function() {
const currentScrollY = window.scrollY;
if (currentScrollY > lastScrollY) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
lastScrollY = currentScrollY;
});
节流优化滚动事件
滚动事件可能触发频繁,使用节流(throttle)可以优化性能。

function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('scroll', throttle(function() {
console.log('节流后的滚动事件');
}, 100));
滚动到指定元素
使用element.scrollIntoView可以让页面滚动到指定元素的位置。
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth'
});
获取滚动位置
通过window.scrollY和window.scrollX可以获取当前页面的滚动位置。
console.log('垂直滚动位置:', window.scrollY);
console.log('水平滚动位置:', window.scrollX);
滚动事件兼容性
对于旧版浏览器,可以使用mousewheel或DOMMouseScroll事件作为备选方案。
window.addEventListener('mousewheel', handleWheel); // Chrome, Safari
window.addEventListener('DOMMouseScroll', handleWheel); // Firefox
function handleWheel(event) {
const delta = event.detail ? -event.detail : event.wheelDelta;
console.log(delta);
}






