js实现走马灯效果
使用CSS动画实现走马灯
通过CSS的@keyframes和animation属性实现水平滚动的走马灯效果。HTML结构需将内容包裹在双层容器中,外层设置overflow: hidden,内层通过动画横向移动。
<div class="marquee-container">
<div class="marquee-content">
<!-- 这里放置需要滚动的内容,重复多次确保无缝衔接 -->
<span>走马灯内容1 | 走马灯内容2 | 走马灯内容3 | </span>
<span>走马灯内容1 | 走马灯内容2 | 走马灯内容3 | </span>
</div>
</div>
.marquee-container {
overflow: hidden;
white-space: nowrap;
width: 100%;
}
.marquee-content {
display: inline-block;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
使用JavaScript动态控制
通过定时器动态修改元素的transform属性,适合需要精确控制暂停、速度等交互的场景。

const marquee = document.querySelector('.marquee-content');
let position = 0;
const speed = 1;
function animate() {
position -= speed;
if (position <= -marquee.scrollWidth / 2) {
position = 0;
}
marquee.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
}
animate();
响应式处理
当内容宽度不足时需要动态复制内容元素,确保无缝滚动效果。

function initMarquee() {
const container = document.querySelector('.marquee-container');
const content = document.querySelector('.marquee-content');
// 复制内容直到填满两倍容器宽度
while (content.scrollWidth < container.offsetWidth * 2) {
content.innerHTML += content.innerHTML;
}
}
window.addEventListener('resize', initMarquee);
initMarquee();
使用第三方库
如需复杂效果可考虑专用库:
swiper.js:支持触摸滑动和响应式断点slick-carousel:提供丰富的配置选项vue-marquee:Vue专用组件
安装示例(以Swiper为例):
npm install swiper
import Swiper from 'swiper';
new Swiper('.marquee-container', {
loop: true,
autoplay: { delay: 0 },
speed: 5000,
allowTouchMove: false,
slidesPerView: 'auto'
});
性能优化建议
- 使用
will-change: transform提升动画性能 - 避免频繁的DOM操作,优先使用CSS动画
- 移动端考虑使用
requestAnimationFrame替代setInterval - 隐藏时停止动画以节省资源:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
entry.target.style.animationPlayState =
entry.isIntersecting ? 'running' : 'paused';
});
});
observer.observe(document.querySelector('.marquee-container'));






