jq文字循环跑马灯
时间: 2023-06-22 10:29:44 浏览: 53
如果您希望使用jQuery实现文字的循环跑马灯效果,可以利用jQuery的动画函数和定时器函数来实现。以下是一个示例代码:
```html
<div class="marquee">
<div class="marquee-content">
<p>这是第一个需要滚动的文字</p>
<p>这是第二个需要滚动的文字</p>
</div>
</div>
```
```css
.marquee {
overflow: hidden;
position: relative;
white-space: nowrap; /* 防止文字换行 */
}
.marquee-content {
position: absolute;
top: 0;
left: 0;
display: inline-block;
}
.marquee p {
display: inline-block;
margin: 0;
padding: 0 20px; /* 调整文字之间的间距 */
line-height: 50px; /* 调整文字垂直居中 */
}
```
```javascript
$(document).ready(function() {
var marqueeWidth = $('.marquee').width(); // 获取容器宽度
var contentWidth = $('.marquee-content').width(); // 获取内容宽度
var marqueeOffset = marqueeWidth - contentWidth; // 计算滚动距离
var speed = 50; // 滚动速度,调整间隔时间即可调整滚动速度
var delay = 2000; // 停留时间,调整即可调整停留时间
var timer;
function marquee() {
$('.marquee-content').animate({
left: marqueeOffset + 'px'
}, contentWidth * 30 / speed, 'linear', function() {
timer = setTimeout(function() {
$('.marquee-content').animate({
left: '0'
}, contentWidth * 30 / speed, 'linear', function() {
marquee();
});
}, delay);
});
}
// 开始滚动
timer = setTimeout(marquee, delay);
// 鼠标悬停时停止滚动,移开时继续滚动
$('.marquee').hover(function() {
clearTimeout(timer);
}, function() {
timer = setTimeout(marquee, delay);
});
});
```
这样,两个p标签内的文字就会在循环跑马灯效果下进行滚动,当鼠标悬停在容器上时,滚动停止,移开后继续滚动。您可以根据需要调整滚动速度、停留时间等参数。