js实现div自动滚动
使用 scrollTop 和定时器实现滚动
通过修改 scrollTop 属性并结合 setInterval 实现平滑滚动效果。以下是一个基础示例代码:
const div = document.getElementById('scrollableDiv');
let scrollStep = 1;
const scrollInterval = setInterval(() => {
div.scrollTop += scrollStep;
if (div.scrollTop >= div.scrollHeight - div.clientHeight) {
clearInterval(scrollInterval); // 到达底部停止
}
}, 20);
使用 requestAnimationFrame 优化性能
requestAnimationFrame 比 setInterval 更适合动画场景,能避免卡顿并节省资源:

const div = document.getElementById('scrollableDiv');
let scrollPosition = 0;
function autoScroll() {
scrollPosition += 1;
div.scrollTop = scrollPosition;
if (scrollPosition < div.scrollHeight - div.clientHeight) {
requestAnimationFrame(autoScroll);
}
}
requestAnimationFrame(autoScroll);
支持反向滚动与循环滚动
添加方向控制和循环逻辑,实现更灵活的滚动行为:

const div = document.getElementById('scrollableDiv');
let scrollStep = 1;
let direction = 1; // 1向下,-1向上
function scrollLoop() {
div.scrollTop += scrollStep * direction;
// 到达底部或顶部时反向
if (div.scrollTop >= div.scrollHeight - div.clientHeight) {
direction = -1;
} else if (div.scrollTop <= 0) {
direction = 1;
}
requestAnimationFrame(scrollLoop);
}
scrollLoop();
使用 CSS Scroll Behavior 平滑过渡
结合 CSS 的 scroll-behavior: smooth 属性实现原生平滑效果:
<style>
#scrollableDiv {
scroll-behavior: smooth;
overflow-y: auto;
height: 200px;
}
</style>
<script>
const div = document.getElementById('scrollableDiv');
setInterval(() => {
if (div.scrollTop !== div.scrollHeight) {
div.scrollTop += 1;
} else {
div.scrollTop = 0; // 循环复位
}
}, 20);
</script>
滚动到特定元素
实现自动滚动到容器内的指定子元素位置:
const container = document.getElementById('scrollContainer');
const targetElement = document.getElementById('target');
container.scrollTop = targetElement.offsetTop - container.offsetTop;
注意事项
- 滚动速度可通过调整
scrollStep值或时间间隔控制 - 移动端需考虑触摸事件冲突,可能需要添加
passive: true选项 - 大量内容滚动时建议使用虚拟滚动技术优化性能
- 清除定时器或动画帧时使用
clearInterval或cancelAnimationFrame





