使用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秒钟,将其从第二个中移除并将其添加到第三个。当它到达终点时,它会循环回来。
答案 0 :(得分: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);
答案 1 :(得分:1)
如果您想创建一个简单的无限旋转新闻项,您可以尝试jQuery cycle plugin来执行此操作。