creating a Javascript-based news ticker
I'm开发者_如何学编程 creating a ticker of sorts, and need it to be running until the page is obviously closed or navigated away from.
This script will just be cycling through li (this is what I've got so far):
$("li").hide(); //hides all "li" onload
var lis = $("ul").children("li").size(); //counts how many "li"s there are
var count = 0;
while(true)
{
count++;
if(count>lis) //checks if count needs to be reset
count = 1;
$("li:nth-child(" + count + ")").fadeIn('slow');
setTimeout('', 4000);
}
Obviously the page won't load because of the the infinite loop. Does anyone have any suggestions about how I should go about this?
var ticker = $('ul.ticker');
ticker.children(':first').show().siblings().hide();
setInterval(function() {
ticker.find(':visible').fadeOut(function() {
$(this).appendTo(ticker);
ticker.children(':first').show();
});
},2000);
demo
You should have your setTimeout point to the function that you want to have fire each time, and have that function also call setTimeout again. It's effectively infinite polling, but with the built-in delay. It also lets you set a flag if you want to break the (i.e. by not calling setTimeout again).
There is also something else like a jquery plugin (jQuery webTicker) that does all the work for you. For example you can just do an unsorted list
<ul id='webticker'>
<li>text</li>
</ul>
use jquery on top of it
jQuery('#webticker').webTicker();
and this will automatically start your rotating script you will also need some additional CSS which is provided along the plugin itself for styling which can be modified. The script includes and automatic stop function when mouse is on top of the webticker whilst you can have fade in and fade out effects as explained in the webticker example on the download website
To add to Reigel's brilliant answer,
var ticker = $('ul.ticker');
ticker.children(':first').show().siblings().hide();
setInterval(function() {
ticker.find(':visible').fadeOut(function() {
$(this).appendTo(ticker);
// fadeIn() rather than show() here to create a continuously fading effect.
ticker.children(':first').fadeIn();
});
},2000);
精彩评论