jquery跑马灯
jQuery跑马灯实现方法
方法一:使用animate()实现横向滚动
$(function() {
function scrollText() {
$(".marquee").animate({marginLeft: "-=1px"}, 0, function() {
if (parseInt($(this).css("margin-left")) <= -$(this).width()) {
$(this).css("margin-left", $(this).parent().width());
}
scrollText();
});
}
scrollText();
});
HTML结构:
<div class="marquee-container" style="width: 300px; overflow: hidden;">
<div class="marquee" style="white-space: nowrap;">
这里是需要滚动显示的文本内容...
</div>
</div>
方法二:使用CSS3动画结合jQuery控制
CSS部分:
.marquee {
display: inline-block;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
jQuery控制:
$(".marquee").on("mouseenter", function() {
$(this).css("animation-play-state", "paused");
}).on("mouseleave", function() {
$(this).css("animation-play-state", "running");
});
方法三:使用jQuery Marquee插件
-
引入插件文件:
<script src="https://cdn.jsdelivr.net/npm/jquery.marquee@1.5.0/jquery.marquee.min.js"></script> -
初始化:
$('.marquee').marquee({ duration: 15000, gap: 50, delayBeforeStart: 0, direction: 'left', duplicated: true });
方法四:垂直滚动实现
$(function() {
var $marquee = $('.vertical-marquee');
var height = $marquee.height();
$marquee.css('top', height);
function scrollVertical() {
$marquee.animate({top: -height}, 10000, 'linear', function() {
$marquee.css('top', height);
scrollVertical();
});
}
scrollVertical();
});
注意事项
- 对于大量内容或复杂动画,建议使用CSS3动画以获得更好的性能
- 考虑添加暂停/继续功能,提升用户体验
- 响应式设计时需注意容器宽度变化对动画的影响
- 移动端设备可能需要调整动画持续时间
以上方法可根据实际需求选择使用,插件方式实现最为简单,自定义代码则灵活性更高。







