我正在开发一个在 div 主体内循环文本的自动收报机。我可以让它以指定的速率移动文本,但我无法弄清楚如何让 JQuery 循环文本。一旦 div 中的内容到达末尾,我如何将它循环回去,同时仍然显示尾部的其余内容?
代码:
var left = -500;
$(document).ready(function(e){
function tick() {
left++;
$(".ticker-text").css("margin-left", -left + "px");
setTimeout(tick, 16);
}
tick();
});
html:
<div class = "ticker-container">
<div class = "ticker-text">
start text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text end
</div>
</div>
最佳答案
当它变得太左时,只需重置边距:
var width = $('.ticker-text').width(),
containerwidth = $('.ticker-container').width(),
left = containerwidth;
$(document).ready(function(e){
function tick() {
if(--left < -width){
left = containerwidth;
}
$(".ticker-text").css("margin-left", left + "px");
setTimeout(tick, 16);
}
tick();
});
请注意,必须更改 CSS,以便 .ticker-text
假定其内容的宽度,而不是您指定的 1000%
:
.ticker-text {
height: 150%;
white-space:nowrap;
display:inline-block;
}
这是一个演示:http://jsfiddle.net/fHd4Z/
关于javascript - 如何在 JQuery 中创建一个水平循环的自动收报机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15755525/