js实现鼠标滚动
监听鼠标滚动事件
在JavaScript中,可以通过监听wheel事件来捕获鼠标滚动行为。wheel事件会在用户滚动鼠标滚轮或触摸板时触发。
window.addEventListener('wheel', function(event) {
console.log(event.deltaY); // 输出垂直滚动量
});
event.deltaY表示垂直方向的滚动量,正值表示向下滚动,负值表示向上滚动。event.deltaX表示水平方向的滚动量。
平滑滚动效果
要实现平滑滚动效果,可以使用window.scrollBy()或window.scrollTo()方法,结合requestAnimationFrame实现动画效果。
function smoothScroll(distance) {
const duration = 1000; // 动画持续时间(毫秒)
const start = window.pageYOffset;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start + distance * progress);
if (progress < 1) {
requestAnimationFrame(scrollStep);
}
}
requestAnimationFrame(scrollStep);
}
window.addEventListener('wheel', function(event) {
event.preventDefault(); // 阻止默认滚动行为
smoothScroll(event.deltaY);
});
滚动到特定元素
要实现滚动到页面中的特定元素,可以使用Element.scrollIntoView()方法。这个方法可以接受一个配置对象,用于指定滚动行为。
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth', // 平滑滚动
block: 'start' // 垂直对齐方式
});
自定义滚动速度
通过修改平滑滚动函数,可以自定义滚动速度。以下示例增加了速度控制参数。
function smoothScroll(distance, speed = 1) {
const duration = 1000 / speed;
const start = window.pageYOffset;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start + distance * progress);
if (progress < 1) {
requestAnimationFrame(scrollStep);
}
}
requestAnimationFrame(scrollStep);
}
防抖处理
为了防止滚动事件触发过于频繁,可以使用防抖(debounce)技术来优化性能。
let debounceTimer;
window.addEventListener('wheel', function(event) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
smoothScroll(event.deltaY);
}, 100); // 延迟100毫秒执行
});
水平滚动
除了垂直滚动,还可以实现水平滚动。以下示例展示了如何监听水平滚动并平滑滚动。
function smoothScrollHorizontal(distance) {
const duration = 1000;
const start = window.pageXOffset;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(start + distance * progress, 0);
if (progress < 1) {
requestAnimationFrame(scrollStep);
}
}
requestAnimationFrame(scrollStep);
}
window.addEventListener('wheel', function(event) {
event.preventDefault();
smoothScrollHorizontal(event.deltaX);
});
兼容性处理
不同浏览器可能对滚动事件的支持有所不同。可以使用mousewheel事件作为wheel事件的备用方案。

const scrollEvent = 'onwheel' in document ? 'wheel' : 'mousewheel';
window.addEventListener(scrollEvent, function(event) {
console.log(event.deltaY);
});






