js实现无缝跑马灯效果
使用CSS动画实现无缝跑马灯
通过CSS的@keyframes和animation属性可以轻松实现无缝滚动效果。HTML结构需将内容复制一份以实现无缝衔接。
<div class="marquee">
<div class="content">这里是需要滚动的内容,内容长度需超过容器宽度</div>
<div class="content" aria-hidden="true">这里是需要滚动的内容,内容长度需超过容器宽度</div>
</div>
.marquee {
width: 100%;
overflow: hidden;
white-space: nowrap;
position: relative;
}
.content {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
使用JavaScript实现动态控制
通过定时器动态修改元素的transform属性,可灵活控制速度和暂停。

const marquee = document.querySelector('.marquee');
const content = document.querySelector('.content');
let position = 0;
const speed = 1; // 像素/帧
function animate() {
position -= speed;
if (position <= -content.offsetWidth) {
position = 0;
}
content.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
}
animate();
// 暂停/恢复控制
marquee.addEventListener('mouseenter', () => {
content.style.animationPlayState = 'paused';
});
marquee.addEventListener('mouseleave', () => {
content.style.animationPlayState = 'running';
});
使用Web Components封装
创建一个可复用的自定义元素,支持参数配置。

class MarqueeElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.speed = parseInt(this.getAttribute('speed')) || 5;
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
overflow: hidden;
}
.wrapper {
display: inline-flex;
white-space: nowrap;
}
</style>
<div class="wrapper">
<slot></slot>
<slot></slot>
</div>
`;
this.startAnimation();
}
startAnimation() {
const wrapper = this.shadowRoot.querySelector('.wrapper');
let position = 0;
const animate = () => {
position -= this.speed;
if (position <= -this.offsetWidth) {
position = 0;
}
wrapper.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
};
animate();
}
}
customElements.define('marquee-element', MarqueeElement);
使用方式:
<marquee-element speed="3">
<span>自定义跑马灯内容</span>
</marquee-element>
性能优化建议
避免使用left/top属性而采用transform,利用硬件加速提升性能。对于大量内容的跑马灯,建议使用Canvas渲染。
const canvas = document.getElementById('marqueeCanvas');
const ctx = canvas.getContext('2d');
let textPos = canvas.width;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText('Canvas实现的跑马灯', textPos, 20);
textPos -= 2;
if (textPos < -200) textPos = canvas.width;
requestAnimationFrame(draw);
}
// 设置字体需在测量文本宽度前
ctx.font = '16px Arial';
draw();
以上方案可根据实际需求选择,CSS方案适合简单场景,JavaScript方案提供更多控制,Web Components方案适合组件化开发,Canvas方案适合高性能需求。






