开发者

jquery, timer or chaining functions?

开发者 https://www.devze.com 2022-12-17 06:10 出处:网络
ho开发者_如何学编程w best to go about cycling through li\'s and repeating? should i use a timer or is there a better way?

ho开发者_如何学编程w best to go about cycling through li's and repeating?

should i use a timer or is there a better way?

for example, i want to display li one at a time. when i hit the end i want to go back to top and start again.


Not sure if I understood your question correctly, but I'll have a stab at it.

Timers are useful when performing animations, or if you think there's going to be a lot of iterations (so as to not hog the thread).

If you're just creating a few LI elements and appending them to a UL element, and you don't want them to be shown incrementally (like in an animation), just use a for loop.


The new jQuery delay() could come in handy here.

$(document).ready(function(){
    $('ul li').hide();

    function loopLi(element){
       element.fadeIn('slow').delay(5*1000).fadeOut('slow');
       var newElement;
       if(element.is(':last')){
          newElement = element.parents('ul').find('li:first');
       }else{
          newElement = element.next();
       }

       loopLi(newElement);
    }

    loopLi($('ul li:first'));

});

UPDATE:

.delay() isn't all that I thought it would be. Seems to work in an asynchronous manner, allowing other functions to be called before the li fades in. Here's a better way, with an interval

$(document).ready(function(){
    $('li:first').addClass('current');
    $('li:not(:first)').hide();

    var slideshow = setInterval(function (){
       $('li.current').fadeOut('slow');
       var nextElement;
       if($('li.current').is(':eq('+ $('li').length +')')){
         nextElement = $('li:first');
       }else{
         nextElement = $('li.current').next();
       }

       $('li.current').hide().removeClass('current');
       nextElement.addClass('current').fadeIn('slow');
    }, 10*1000);

});


If you need more feature you could use jCarousel or another carousel type plugin. Not sure what you need your presentation to look like so this may or may not be more trouble than its worth.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号