jquery 跑马灯
以下是实现 jQuery 跑马灯效果的几种常见方法,适用于文字或内容的横向滚动展示:
方法一:使用 animate() 实现基础跑马灯
通过调整元素的 margin-left 或 left 属性实现滚动效果。需确保容器设置 overflow: hidden。
$(document).ready(function() {
function marquee() {
$(".marquee-content").animate({marginLeft: "-=1px"}, 10, "linear", function() {
if (parseInt($(this).css("marginLeft")) <= -$(this).width()) {
$(this).css("marginLeft", $(".marquee-container").width());
}
marquee();
});
}
marquee();
});
HTML 结构:

<div class="marquee-container" style="width: 300px; overflow: hidden;">
<div class="marquee-content" style="white-space: nowrap;">
这里是需要滚动展示的文字内容...
</div>
</div>
方法二:克隆内容无限滚动
通过克隆内容并拼接,实现无缝循环滚动效果。
$(document).ready(function() {
var $marquee = $(".marquee-content");
$marquee.clone().appendTo($marquee.parent());
function scroll() {
var scrollWidth = $marquee.width() / 2;
$(".marquee-container").animate({scrollLeft: scrollWidth}, 10000, "linear", function() {
$(this).scrollLeft(0);
scroll();
});
}
scroll();
});
方法三:使用 CSS3 动画 + jQuery 控制
结合 CSS3 的 @keyframes 实现更流畅的动画,通过 jQuery 添加类名触发。

CSS:
.marquee-content {
display: inline-block;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
jQuery 控制暂停/继续:
$(".marquee-container").hover(
function() { $(".marquee-content").css("animation-play-state", "paused"); },
function() { $(".marquee-content").css("animation-play-state", "running"); }
);
注意事项
- 性能优化:对于长内容,优先使用 CSS3 动画以减少重绘。
- 响应式适配:通过监听窗口大小变化重新计算滚动距离:
$(window).resize(function() { $(".marquee-content").css("marginLeft", "0"); }); - 插件扩展:如需复杂功能(如垂直滚动、动态内容),可考虑插件如
jquery.marquee。
以上方法可根据实际需求调整速度(修改动画时间)或方向(修改 marginLeft 为 marginTop 实现垂直滚动)。






