js实现网页滑动
实现网页滑动的 JavaScript 方法
监听滚动事件
通过 window.addEventListener 监听 scroll 事件,可以实时获取滚动位置。示例代码:
window.addEventListener('scroll', function() {
console.log(window.scrollY); // 输出当前垂直滚动位置
});
平滑滚动到指定位置
使用 window.scrollTo() 方法实现平滑滚动,通过 behavior: 'smooth' 启用动画效果:
// 滚动到页面顶部
window.scrollTo({
top: 0,
behavior: 'smooth'
});
// 滚动到指定元素
document.getElementById('target').scrollIntoView({
behavior: 'smooth'
});
自定义滚动动画
通过 requestAnimationFrame 实现更灵活的滚动动画控制:

function smoothScrollTo(targetY, duration = 1000) {
const startY = window.scrollY;
const distance = targetY - startY;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, startY + distance * easeInOutQuad(progress));
if (progress < 1) requestAnimationFrame(animation);
}
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
requestAnimationFrame(animation);
}
滚动节流优化
高频滚动事件可能影响性能,使用节流函数优化:
function throttle(func, limit) {
let inThrottle;
return function() {
if (!inThrottle) {
func.apply(this, arguments);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('scroll', throttle(function() {
// 你的滚动处理逻辑
}, 100));
滚动方向检测
通过比较当前和上一次滚动位置判断方向:

let lastScroll = 0;
window.addEventListener('scroll', function() {
const currentScroll = window.scrollY;
if (currentScroll > lastScroll) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
lastScroll = currentScroll;
});
滚动到特定位置触发事件
使用 IntersectionObserver API 实现元素进入视口时触发动作:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('active');
}
});
});
document.querySelectorAll('.observe').forEach(el => {
observer.observe(el);
});
禁用页面滚动
临时禁用页面滚动的实现方法:
// 禁用滚动
document.body.style.overflow = 'hidden';
// 恢复滚动
document.body.style.overflow = '';






