开发者

Change DIV CSS on a timer using jQuery

Change DIV CSS on a timer using jQuery

I'm new to javascript and was just wondering the best way to go about开发者_C百科 changing the background image (only 2 images) of a DIV say like every 10 seconds. Thanks :)


This should do it for you : http://jsfiddle.net/U9GCM/

$(document).ready(function(){
var setFirst = $('.set').first();    
setFirst.addClass('active');
setTimeout(function(){change_background();},1000);
});

function change_background(){
    var setFirst = $('.set').first(),
        setActive = $('.active'),
        setNext = setActive.next(),
        setCheckActive = setActive.attr('id'),
        setCheckLast = $('.set').last().attr('id');

    if(setCheckActive == setCheckLast){
        setNext = setFirst;
        }

    $('.active').removeClass('active');
    setNext.addClass('active');
    setTimeout(function(){change_background()},1000);
    }

You can add as many divs as you want, just change 1000 to 10000 for ten seconds.

Hope it helps.


Try something like this:

$(document).ready(function(){
   setTimeout('setbackground()',10000);
});

function setbackground(){ 
  // change you image here
  setTimeout('setbackground()',10000); // to change the image in 10 seconds
}


jsfiddle demo

alternate CSS classes (ie bg1 <--> bg2) with a setInterval function

var body = document.getElementsByTagName('body')[0],
    switchBG = function() {
        var bgTimer = setInterval(function() {
            body.className = (body.className === "bg2" ? "bg1" : "bg2");
        }, 10000 /* 10000 ms = 10 sec */);
    };
switchBG();

this is straight js


$(document).ready(function(){
   var i = 0;
   var images = newArray("image1.jpg","image2.png","image3.jpg");
   setTimeout('changeBack(i, images)',10000);
});

function changeBack(i, images) {
i++;
if(i > images.length) {
    i = 0;
}
$('#changeBackInThisId').css('background-image', images[i]);
setTimeout(changeBack(i, images), 10000);
}

I hope it works :-)

Or you can have any number of divs in your code with style="display: none" (besides the first of them) and each 10 seconds sets display: block; to one of them.


Here's a plugin type answer: http://jsfiddle.net/EpGsc/


var time = 10000; // Ten seconds 
var timer = setInterval(function() {

    $('#myDiv, #myOtherDiv').css('background-image', '/new/img/path.jpg');

}, time);

Not tested but should work. I'll work on an example.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜