每隔几秒从html中

时间:2016-04-27 10:02:50

标签: javascript jquery html

我试图每3秒更换一次div上的类。类在数组中,应删除前一个类并添加下一个类。 "首先"应该是第一,然后"第二",然后"第三"并回到循环。



jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'];

    function changeBackground() {
        var className = $('#main').attr('class');
        if (className == null)
            className = images[0];

        $('#main').removeClass(function () {
            var newClass = // find value in array and take next value, if end of array get first
                $(this).addClass(newClass);
        });
    }

    changeBackground();
    setInterval(changeBackground, 2000);
});

<div id="main"></div>

    
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
 jQuery(document).ready(function($) {
     var images = ['first', 'second', 'third'],
     	i = 0;

     function changeBackground() {
         $('#main').attr('class', images[i++]);
         i = i % images.length;
     }

     changeBackground();
     setInterval(changeBackground, 2000);
 });
&#13;
#main {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.first {
    background-color: #f01 !important;
}

.second {
    background-color: blue;
}

.third {
    background-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div id="main"></div>
&#13;
&#13;
&#13;

enter link description here