循环上课

时间:2012-12-05 11:11:27

标签: javascript jquery css cycle

我有下面的html,我希望自动循环通过它。它目前通过onclick手动完成。但是我怎么能让它循环呢?它基本上只是更改包装器div上的类名称,如下所示:

<body>
    <div id="client-relations-bg" class="background_tab1">
        ...content...
    </div>
</body>

我在这里有班级图像信息:

<style type="text/css">
    #client-relations-bg.background_tab1{background: url('/media/2/background-image-1.png') no-repeat center top;}
    #client-relations-bg.background_tab2{background: url('/media/32/background-image-6.jpg') no-repeat center top;}
    #client-relations-bg.background_tab3{background: url('/media/17/background-image-3.jpg') no-repeat center top;}
    #client-relations-bg.background_tab4{background: url('/media/12/background-image-2.png') no-repeat center top;}
    #client-relations-bg.background_tab5{background: url('/media/22/background-image-4.jpg') no-repeat center top;}
    #client-relations-bg.background_tab6{background: url('/media/37/background-image-7.jpg') no-repeat center top;}
    #client-relations-bg.background_tab7{background: url('/media/2900/Header_image.jpg') no-repeat center top;}
</style>

所以我需要这样:class="background_tab1"tab1之间循环到tab7

4 个答案:

答案 0 :(得分:3)

您实际上不需要使用jQuery

(function(){
    var interval = 1000;
    var currentBackgroundId = 1;
    window.setInterval(function(){
        currentBackgroundId++;
        if (currentBackgroundId == 8) currentBackgroundId = 1;

        var element = document.getElementById('client-relations-bg');
        element.className = 'background_tab' + currentBackgroundId;
    }, interval);
})();

答案 1 :(得分:1)

jQuery有很好的类操作方法。您需要做的就是解析当前的类以查找当前的数字,或者将其存储在全局变量中,并在设置下一个时执行i++ % 7

答案 2 :(得分:1)

如果你事先知道你的类名,那就行了:

var
  classList = ['background_tab1', 'background_tab2', 'background_tab3'],
  $el = $('#client-relations-bg');

(function next() {
  setTimeout(function () {
    classList.push(classList.shift());
    $el.removeClass().addClass(classList[0]);
    next();
  }, 2000);
}());

http://jsfiddle.net/c2uqp/

答案 3 :(得分:1)

这是一种方法:

var classes = [
    "background_tab1",
    "background_tab2",
    "background_tab3",
    "background_tab4",
    "background_tab5",
    "background_tab6",
    "background_tab7"
];
setInterval(function() {
    var $div = $("#client-relations-bg");
    $.each(classes, function(i, c) {
        if ($div.hasClass(c)) {
            var j = (i + 1) % classes.length;
            $div.removeClass(c).addClass(classes[j]).text(classes[j]);
            return false;
        }
    });
}, 2000);

});

Demo here