简体   繁体   中英

JS and CSS changing image on interval

i am wanting to have my webpage display a different background every minute or there abouts, the image is also quite large so it would have to fit using cover. The background is a background-image on the body here is my css code

#body {
  background-image: url("home.jpg");
  background-position: top;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  margin: 0px;
}

and i want to have the script change the url (or source img) to a differrent one every minute. I tryed this with setInteval and onLoad in html but i cant crack it!

Thanks very much

An easiest solution is to use jQuery backstretch plugin .

  $.backstretch([
      "http://dl.dropbox.com/u/515046/www/outside.jpg",
      "http://dl.dropbox.com/u/515046/www/garfield-interior.jpg",
      "http://dl.dropbox.com/u/515046/www/cheers.jpg"
  ], {duration: 3000, fade: 750});

Here is a jQuery only solution.

$(function() {
    var body = $('body');
    var backgrounds = new Array(
        'url(https://dl.dropbox.com/u/515046/www/outside.jpg)',
        'url(https://dl.dropbox.com/u/515046/www/garfield-interior.jpg)'
    );
    var current = 0;

    function nextBackground() {
        body.css(
            'background',
            backgrounds[current = ++current % backgrounds.length]
        );

        setTimeout(nextBackground, 10000);
    }
    setTimeout(nextBackground, 10000);
    body.css('background', backgrounds[0]);
});

Reference

IMHO this code snippet will get you started.

 // get reference to body var main = document.body; // next two lines of code allow toggle between colors to demonstrate this example. var color = function() { var col = "red"; return function() { col = (col === "red" ? "blue" : "red"); return col; }; }; var nextColor = color(); // using setTimeout instead of setInterval function loop() { var timeoutId = setTimeout(function() { console.log('clearing', timeoutId) clearTimeout(timeoutId); main.style.background = nextColor(); loop(); }, 1000); } 

https://jsfiddle.net/4L4bww5r/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM