1

使用jquery每4秒向div添加一个类的最佳方法是什么?

<div class="34 post">
<img width="311" height="417" src="#" class="#" alt="newspapers" />
<h2><a href="#">Headline News Part 2</a></h2>
<p>testing new content</p>
</div>

<div class="9 post">
<img width="311" height="417" src="#" class="#" alt="newspapers" />
<h2><a href="#">Headline News Part 2</a></h2>
<p>testing new content</p>
</div>

<div class="6 post">
<img width="311" height="417" src="#" class="#" alt="newspapers" />
<h2><a href="#">Headline News Part 2</a></h2>
<p>testing new content</p>
</div>

所以我希望第一个有一个“显示”类,然后在 4 秒后,我想删除那个类并将其添加到第二个类。然后再过 4 秒后,将其从第二个中删除并将其添加到第三个中。当它到达终点时,它会循环回来。

4

2 回答 2

3
var $postDivs = $('div.post'), // assuming these won't change
    i = -1,
    CLASS_NAME = 'foo';

setInterval(function () {
    $postDivs.eq(i).removeClass(CLASS_NAME);
    i = (i+1) % $postDivs.length;
    $postDivs.eq(i).addClass(CLASS_NAME);
}, 4000);

http://jsfiddle.net/mattball/k2sJy/

于 2012-04-10T20:33:04.513 回答
1

If you want to create a simple infinite rotation of news items, you may try jQuery cycle plugin for doing this.

于 2012-04-10T20:38:33.960 回答