js实现无缝滚动代码
以下是一个基于JavaScript实现的无缝滚动方案,包含横向和纵向两种常见场景的代码实现:

横向无缝滚动
<div id="scroll-container" style="width:500px; overflow:hidden; white-space:nowrap;">
<div id="scroll-content" style="display:inline-block;">
<!-- 内容元素 -->
</div>
</div>
const container = document.getElementById('scroll-container');
const content = document.getElementById('scroll-content');
const clone = content.cloneNode(true);
container.appendChild(clone);
let scrollPos = 0;
function scrollHorizontally() {
scrollPos += 1;
if(scrollPos >= content.offsetWidth) {
scrollPos = 0;
}
container.scrollLeft = scrollPos;
requestAnimationFrame(scrollHorizontally);
}
scrollHorizontally();
纵向无缝滚动
<div id="scroll-container" style="height:200px; overflow:hidden;">
<div id="scroll-content">
<!-- 内容元素 -->
</div>
</div>
const container = document.getElementById('scroll-container');
const content = document.getElementById('scroll-content');
const clone = content.cloneNode(true);
container.appendChild(clone);
let scrollPos = 0;
function scrollVertically() {
scrollPos += 1;
if(scrollPos >= content.offsetHeight) {
scrollPos = 0;
}
container.scrollTop = scrollPos;
requestAnimationFrame(scrollVertically);
}
scrollVertically();
优化版本(带暂停控制)
function createSeamlessScroll(containerId, direction = 'horizontal') {
const container = document.getElementById(containerId);
const content = container.firstElementChild;
const clone = content.cloneNode(true);
container.appendChild(clone);
let scrollPos = 0;
let isPaused = false;
let animationId;
function scroll() {
if(isPaused) return;
if(direction === 'horizontal') {
scrollPos += 1;
if(scrollPos >= content.offsetWidth) scrollPos = 0;
container.scrollLeft = scrollPos;
} else {
scrollPos += 1;
if(scrollPos >= content.offsetHeight) scrollPos = 0;
container.scrollTop = scrollPos;
}
animationId = requestAnimationFrame(scroll);
}
container.addEventListener('mouseenter', () => { isPaused = true; });
container.addEventListener('mouseleave', () => { isPaused = false; scroll(); });
scroll();
return () => cancelAnimationFrame(animationId);
}
// 使用示例
const stopScroll = createSeamlessScroll('scroll-container', 'vertical');
// 需要停止时调用 stopScroll()
关键实现原理
- 克隆滚动内容并追加到容器末尾
- 当原始内容完全滚出可视区域时重置滚动位置
- 使用requestAnimationFrame实现平滑动画
- 通过判断内容元素的offsetWidth/offsetHeight确定重置点
注意事项
- 确保容器设置overflow:hidden
- 内容元素需要保持连续(横向需white-space:nowrap)
- 移动端可能需要添加touch事件处理
- 性能敏感场景建议使用CSS transform替代scrollTop/Left






