js实现图片滚动效果
使用CSS动画实现图片滚动
通过CSS的@keyframes和animation属性实现无缝滚动效果。将图片容器设置为横向排列,通过动画平移位置。
<style>
.scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.scroll-content {
display: inline-block;
animation: scroll 20s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
</style>
<div class="scroll-container">
<div class="scroll-content">
<img src="image1.jpg" width="200">
<img src="image2.jpg" width="200">
<!-- 更多图片... -->
</div>
<div class="scroll-content" aria-hidden="true">
<img src="image1.jpg" width="200">
<img src="image2.jpg" width="200">
<!-- 重复内容实现无缝滚动 -->
</div>
</div>
使用JavaScript定时器实现
通过setInterval定期修改容器的scrollLeft属性实现平滑滚动。需计算内容宽度和滚动距离。

const container = document.querySelector('.scroll-container');
const content = document.querySelector('.scroll-content');
let scrollPos = 0;
function animate() {
scrollPos += 1;
if (scrollPos >= content.scrollWidth / 2) {
scrollPos = 0;
}
container.scrollLeft = scrollPos;
requestAnimationFrame(animate);
}
animate();
使用第三方库实现
Swiper.js等现成库提供丰富的滚动效果配置:

import Swiper from 'swiper';
new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
slidesPerView: 'auto',
});
响应式处理注意事项
动态计算图片数量与容器宽度:
function initScroll() {
const imgWidth = 200; // 单图宽度
const visibleImgs = Math.ceil(container.offsetWidth / imgWidth);
content.style.width = `${imgWidth * (images.length + visibleImgs)}px`;
}
window.addEventListener('resize', initScroll);
性能优化建议
使用will-change提升渲染性能:
.scroll-content {
will-change: transform;
}
对于大量图片采用虚拟滚动技术,只渲染可视区域内的图片元素。滚动事件建议使用requestAnimationFrame而非直接setInterval。






