js实现内容滚动
使用JavaScript实现内容滚动
使用scrollTo方法平滑滚动
通过window.scrollTo方法可以实现页面滚动到指定位置,结合behavior: 'smooth'可实现平滑滚动效果。
window.scrollTo({
top: 500,
behavior: 'smooth'
});
使用scrollIntoView滚动到元素
DOM元素的scrollIntoView方法可将元素滚动到视口中,支持平滑滚动选项。
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth',
block: 'start'
});
自定义动画实现平滑滚动
通过requestAnimationFrame实现自定义滚动动画,控制滚动过程。
function smoothScrollTo(targetPosition, duration = 1000) {
const startPosition = window.pageYOffset;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
window.scrollTo(0, startPosition + distance * progress);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
监听滚动事件
通过添加滚动事件监听器,可以在滚动过程中执行特定操作。
window.addEventListener('scroll', function() {
console.log('当前滚动位置:', window.pageYOffset);
});
滚动到顶部/底部
实现快速滚动到页面顶部或底部的功能。
// 滚动到顶部
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// 滚动到底部
function scrollToBottom() {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
}
横向滚动控制
对于水平滚动容器,可以使用类似的原理控制横向滚动。
const container = document.querySelector('.horizontal-scroll');
container.scrollTo({
left: 300,
behavior: 'smooth'
});
滚动位置恢复
在SPA应用中,可能需要保存和恢复滚动位置。
// 保存滚动位置
const scrollPos = window.pageYOffset;
// 恢复滚动位置
window.scrollTo(0, scrollPos);
使用CSS实现平滑滚动
在CSS中设置scroll-behavior属性可启用全局平滑滚动效果。

html {
scroll-behavior: smooth;
}
注意事项
- 平滑滚动性能可能受页面复杂度和滚动距离影响
- 移动端设备可能有不同的滚动行为
- 某些浏览器可能需要polyfill支持平滑滚动






