js 实现滚动
实现滚动的方法
使用 window.scrollTo()
window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。
// 滚动到指定位置(x, y)
window.scrollTo(0, 500);
// 使用平滑滚动
window.scrollTo({
top: 500,
behavior: 'smooth'
});
使用 window.scrollBy()
window.scrollBy() 方法相对于当前滚动位置滚动指定的距离。

// 向下滚动 200 像素
window.scrollBy(0, 200);
// 平滑滚动 200 像素
window.scrollBy({
top: 200,
behavior: 'smooth'
});
使用 Element.scrollIntoView()
scrollIntoView() 方法可以让元素滚动到可视区域。支持平滑滚动选项。
const element = document.getElementById('target');
element.scrollIntoView({
behavior: 'smooth',
block: 'start' // 或 'center', 'end', 'nearest'
});
监听滚动事件
可以通过监听 scroll 事件来执行滚动相关的逻辑。

window.addEventListener('scroll', () => {
console.log('当前滚动位置:', window.scrollY);
});
使用 requestAnimationFrame 实现自定义动画
如果需要更复杂的滚动动画,可以使用 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, 1500);
滚动到页面顶部或底部
可以使用 scrollTo 或 scrollIntoView 快速滚动到页面顶部或底部。
// 滚动到顶部
window.scrollTo({
top: 0,
behavior: 'smooth'
});
// 滚动到底部
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});






