jquery 跑马灯
jQuery 跑马灯实现方法
使用 jQuery 实现跑马灯效果可以通过多种方式完成,以下是几种常见的方法:
水平滚动跑马灯
通过设置 marquee 元素的水平滚动动画实现:
$(document).ready(function() {
function scrollMarquee() {
$('.marquee').animate({marginLeft: '-=1px'}, 10, 'linear', function() {
if (parseInt($(this).css('marginLeft')) <= -$(this).width()) {
$(this).css('marginLeft', $(window).width());
}
scrollMarquee();
});
}
scrollMarquee();
});
CSS3 动画结合 jQuery
利用 CSS3 的 animation 属性实现更流畅的动画效果:
$(document).ready(function() {
$('.marquee').css({
'animation': 'marquee ' + ($('.marquee').width() / 50) + 's linear infinite'
});
});
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
垂直滚动跑马灯
修改动画方向为垂直滚动:
$(document).ready(function() {
function scrollVertical() {
$('.marquee-vertical').animate({marginTop: '-=1px'}, 50, 'linear', function() {
if (parseInt($(this).css('marginTop')) <= -$(this).height()) {
$(this).css('marginTop', $(window).height());
}
scrollVertical();
});
}
scrollVertical();
});
跑马灯插件推荐
对于更复杂的需求,可以考虑使用专门的 jQuery 插件:

- jQuery Marquee
功能丰富的跑马灯插件,支持多种滚动方向和效果。
$('.marquee').marquee({
duration: 5000,
gap: 50,
delayBeforeStart: 0,
direction: 'left',
duplicated: true
});
- Ticker.js
轻量级的跑马灯解决方案,适合新闻标题等简单应用。
注意事项
- 确保包含 jQuery 库文件
- 考虑响应式设计,在不同屏幕尺寸下测试效果
- 对于大量内容,建议使用
duplicated: true选项实现无缝滚动 - 动画性能优化:使用 CSS3 动画通常比 jQuery 动画更高效
完整示例代码
<!DOCTYPE html>
<html>
<head>
<style>
.marquee {
white-space: nowrap;
overflow: hidden;
width: 100%;
}
.marquee span {
display: inline-block;
padding-left: 100%;
}
</style>
</head>
<body>
<div class="marquee">
<span>这是跑马灯文字内容,可以自定义...</span>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('.marquee').each(function() {
var marquee = $(this);
marquee.marquee = function() {
marquee.find('span').animate(
{'marginLeft': '-=1px'},
10,
'linear',
marquee.marquee
);
};
marquee.marquee();
});
});
</script>
</body>
</html>






