js实现一秒滚动的效果
JavaScript 实现平滑滚动效果
使用 window.scrollTo 方法结合 behavior: 'smooth' 实现平滑滚动:
window.scrollTo({
top: 1000,
behavior: 'smooth'
});
定时滚动实现每秒滚动
通过 setInterval 实现每秒自动滚动一定距离:
let scrollPosition = 0;
const scrollInterval = setInterval(() => {
scrollPosition += 100;
window.scrollTo({
top: scrollPosition,
behavior: 'smooth'
});
if (scrollPosition >= document.body.scrollHeight) {
clearInterval(scrollInterval);
}
}, 1000);
使用 CSS 平滑滚动
在 CSS 中设置全局滚动行为:
html {
scroll-behavior: smooth;
}
滚动到指定元素
滚动到页面中的特定元素:
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth'
});
自定义缓动函数
实现自定义缓动效果的滚动:
function smoothScrollTo(target, duration) {
const start = window.pageYOffset;
const distance = target - start;
let startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = easeInOutQuad(timeElapsed, start, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
function easeInOutQuad(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
requestAnimationFrame(animation);
}
smoothScrollTo(1000, 1000);
注意事项
确保滚动内容高度足够,避免在页面底部继续滚动。
考虑移动设备兼容性,测试不同浏览器的平滑滚动支持情况。

清除定时器防止内存泄漏,特别是在组件卸载时。






