js实现一秒滚动的效果
使用 window.scrollBy 实现平滑滚动
通过 window.scrollBy 方法结合 requestAnimationFrame 实现平滑滚动效果。该方法逐帧调整滚动位置,形成动画效果。
function smoothScrollBy(distance, duration) {
const start = window.pageYOffset;
const startTime = performance.now();
function scrollStep(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollBy(0, distance * progress - (window.pageYOffset - start));
if (progress < 1) {
requestAnimationFrame(scrollStep);
}
}
requestAnimationFrame(scrollStep);
}
// 调用示例:每秒滚动100像素
smoothScrollBy(100, 1000);
使用 CSS scroll-behavior 属性
通过 CSS 的 scroll-behavior: smooth 属性实现原生平滑滚动效果,再通过 JavaScript 触发滚动。
<style>
html {
scroll-behavior: smooth;
}
</style>
<script>
function scrollPerSecond() {
const currentPosition = window.pageYOffset;
window.scrollTo(0, currentPosition + 100);
setTimeout(scrollPerSecond, 1000);
}
scrollPerSecond();
</script>
使用 Element.scrollIntoView 方法
通过循环调用 scrollIntoView 方法实现逐元素滚动效果。
let currentElement = document.body.firstElementChild;
function scrollNextElement() {
if (currentElement) {
currentElement.scrollIntoView({ behavior: 'smooth' });
currentElement = currentElement.nextElementSibling;
setTimeout(scrollNextElement, 1000);
}
}
scrollNextElement();
使用第三方库(如 SmoothScroll)
引入第三方库实现更复杂的滚动效果,例如 smooth-scroll 库。
<script src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.polyfills.min.js"></script>
<script>
const scroll = new SmoothScroll();
let currentPosition = 0;
function autoScroll() {
currentPosition += 100;
scroll.animateScroll(currentPosition);
setTimeout(autoScroll, 1000);
}
autoScroll();
</script>
注意事项
- 移动端设备可能需要处理触摸事件冲突
- 长时间运行的滚动需要添加终止条件
- 性能敏感场景建议使用
requestAnimationFrame - 某些浏览器可能需要 polyfill 来支持平滑滚动 API
以上方法均可实现每秒自动滚动效果,可根据具体需求选择简单 CSS 方案或更可控的 JavaScript 动画方案。







