Dynamically Changing CSS Background Image

前端 未结 5 429
余生分开走
余生分开走 2020-12-10 05:11

What I\'m looking for is a way to make my HTML header tag change background images every few seconds. Any solutions are welcome, as long as it is not to complex.

I h

5条回答
  •  失恋的感觉
    2020-12-10 05:20

    Made a few amendments to your code

    DEMO: http://jsfiddle.net/p77KW/

    var header = $('body');
    
    var backgrounds = new Array(
        'url(http://placekitten.com/100)'
      , 'url(http://placekitten.com/200)'
      , 'url(http://placekitten.com/300)'
      , 'url(http://placekitten.com/400)'
    );
    
    var current = 0;
    
    function nextBackground() {
        current++;
        current = current % backgrounds.length;
        header.css('background-image', backgrounds[current]);
    }
    setInterval(nextBackground, 1000);
    
    header.css('background-image', backgrounds[0]);
    

    Biggest changes (as noted in others comments) is that you have to use apostrophe**'**s, not those funky open and close single-quotes and that your array wasn't correct.

    With these corrections out of the way I simplified a few things:

    1. Increment current then take modulus (I know this is basically what you did but how much easier is that to debug ;))
    2. Target background-image directly
    3. Used setInterval() instead of a double call to setTimeout

提交回复
热议问题