js实现滚动
实现滚动的方法
使用window.scrollTo()
通过window.scrollTo(x, y)可以将页面滚动到指定坐标位置。x表示水平滚动位置,y表示垂直滚动位置。
window.scrollTo(0, 500); // 滚动到垂直位置500px
支持平滑滚动效果,可以传入一个配置对象:
window.scrollTo({
top: 500,
left: 0,
behavior: 'smooth'
});
使用element.scrollIntoView()
通过调用元素的scrollIntoView()方法,可以让元素滚动到视图中。
document.getElementById('target').scrollIntoView({
behavior: 'smooth'
});
使用window.scrollBy()
window.scrollBy(x, y)可以相对于当前位置进行滚动。
window.scrollBy(0, 100); // 向下滚动100px
监听滚动事件
通过监听scroll事件可以获取当前滚动位置或执行滚动相关操作。
window.addEventListener('scroll', function() {
console.log(window.scrollY); // 获取垂直滚动位置
});
使用CSS实现平滑滚动
在CSS中设置scroll-behavior属性可以让页面滚动更平滑。
html {
scroll-behavior: smooth;
}
滚动到页面顶部/底部
使用window.scrollTo()可以轻松实现滚动到页面顶部或底部。
// 滚动到顶部
window.scrollTo(0, 0);
// 滚动到底部
window.scrollTo(0, document.body.scrollHeight);
自定义滚动动画
可以通过requestAnimationFrame实现自定义滚动动画效果。

function scrollToTop(duration) {
const start = window.scrollY;
const startTime = performance.now();
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start * (1 - progress));
if (progress < 1) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}
scrollToTop(1000); // 1秒内滚动到顶部






