jquery跑马灯
jQuery跑马灯实现方法
使用jQuery实现跑马灯效果可以通过多种方式完成,以下是几种常见的方法:

方法一:使用animate()实现横向滚动
$(document).ready(function(){
function scrollText(){
$(".marquee").animate({left: '-=1px'}, 10, 'linear', function(){
if(parseInt($(this).css('left')) <= -$(this).width()){
$(this).css('left', $(this).parent().width());
}
scrollText();
});
}
$(".marquee").css('left', $(".marquee-container").width());
scrollText();
});
<div class="marquee-container" style="overflow:hidden; position:relative; width:500px;">
<div class="marquee" style="position:absolute; white-space:nowrap;">
这里是需要滚动显示的文本内容
</div>
</div>
方法二:使用CSS3动画配合jQuery控制
$(document).ready(function(){
$('.marquee').each(function(){
var duration = $(this).text().length * 0.5;
$(this).css('animation-duration', duration + 's');
});
});
.marquee {
display: inline-block;
white-space: nowrap;
animation: marquee linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
方法三:使用jQuery插件
-
引入jQuery和marquee插件:

<script src="https://cdn.jsdelivr.net/npm/jquery.marquee@1.5.0/jquery.marquee.min.js"></script> -
初始化插件:
$('.marquee').marquee({ duration: 5000, gap: 50, delayBeforeStart: 0, direction: 'left', duplicated: true }); -
HTML结构:
<div class="marquee"> 这里是需要滚动显示的文本内容 </div>
方法四:垂直滚动效果
$(function(){
var $marquee = $('.marquee');
var height = $marquee.height();
$marquee.wrap('<div class="marquee-container"></div>');
$marquee.parent().height(height);
$marquee.clone().appendTo($marquee.parent());
function scroll(){
var first = $marquee.parent().children().first();
var scrollHeight = first.height();
first.animate({marginTop: -scrollHeight}, 1000, 'linear', function(){
first.css('marginTop', 0).appendTo($marquee.parent());
scroll();
});
}
scroll();
});
<div class="marquee" style="height:20px; overflow:hidden;">
<div>第一条消息</div>
<div>第二条消息</div>
<div>第三条消息</div>
</div>
注意事项
- 确保在DOM加载完成后执行jQuery代码,通常使用$(document).ready()
- 对于大量内容或复杂效果,考虑使用专门的插件如jQuery.marquee
- 响应式设计时需要注意容器宽度变化对跑马灯效果的影响
- 性能优化:对于长时间运行的动画,使用CSS3动画通常比jQuery animate()性能更好
- 移动端适配时可能需要调整滚动速度和触发方式
以上方法可以根据实际需求进行调整,如改变滚动方向、速度或添加悬停暂停等功能。






