开发者

Javascript content rotator?

I’ve got the basics of a content rotator done, the only problem is it doesn’t loop itself back to the beginning and I cannot figure out why! It is a very simple javascript script:

window.onload = function() { setInterval("transition()", 5000); }

    function transition()
    {
        var y = document.getElementById("featured").getElementsByTagName("li");
        for (var i=0;i<y.length;i++)
        {
            if (y[i].className == "curre开发者_如何学运维nt")
            {
                y[(i+1)].className = "current";
                y[i].className = "";
                break;
            }
        }
    }

It keeps stopping at the end of the list, basically I just want it to loop. Any help?


You can make this a little smarter by taking advantage of the wonderful language that is Javascript:

window.onload = function() {
  var y = document.getElementById('featured').getElementsByTagName('li');
  var ylen = y.length, index = 0;
  y[0].className = 'current';
  setInterval(function() {
    y[index].className = '';
    index = (index + 1) % ylen;
    y[index].className = 'current';
  }, 5000);
};

When you pre-define the list of <li> elements like that, the function you provide for the interval timer can reference them every time the timer fires. The index variable increments up until it hits the end of the array, and then it'll be set back to zero.


try this:

       if (y[i].className == "current") 
       { 
           if (y[i+1]]
               y[i+1].className = "current";
           else
               y[0].className = "current";
           y[i].className = ""; 
           break; 
       } 


First time you loop you set the last elements class "current". You should put something like

y[0].className = "current"

when you reach and of the loop.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜