JavaScript动态淡出背景图像

时间:2015-01-25 04:17:03

标签: javascript jquery html5 css3 web

我尝试从5张图片以5秒的间隔动态更改应用程序的背景图像,然后重复。

这是我的JS代码:

<script type="text/javascript">
  $(function() {
    var body = $('body');
    var backgrounds = new Array(
      'url(img/bg/bk.jpg)',
      'url(img/bg/nb.jpg)',
      'url(img/bg/la.jpg)',
      'url(img/bg/ts.jpg)',
      'url(img/bg/bh.jpg)'
    );
    var current = 0;
    function nextBackground() {
      body.css(
        'background',
        backgrounds[current = ++current % backgrounds.length]
      );
      setTimeout(nextBackground, 5000);
    }
    setTimeout(nextBackground, 5000);
    body.css('background', backgrounds[0]);
  });
</script>

这是我的CSS:

body { 
  background: no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  padding-top: 40px;
  padding-bottom: 40px;
}

但它不起作用。即使背景是空白的。 <body>没有任何属性。

1 个答案:

答案 0 :(得分:1)

<强> jsBin demo

你的剧本很好,我只改变了几件事:

CSS:

html, body{height:100%;}
body { 
  background: none 50% / cover; /* full background image */
}

jQuery的:

$(function() {
  var body = $('body');
  var backgrounds = [
    '//placehold.it/800x600/cf5&text=1', // no need to `url(` here
    '//placehold.it/800x600/f1f&text=2',
    '//placehold.it/800x600/333&text=3',
    '//placehold.it/800x600/0f0&text=4',
    '//placehold.it/800x600/70f&text=5'
  ];
  var current = 0;

  // Preload all images // Prevent (if possible) white gaps between image load
  for(var i=0; i<backgrounds.length; i++){
    var img = new Image();
    img.src= backgrounds[i];
  }

  function nextBackground() {
    body.css(
      "background-image", // Use background-image instead of `background`
       "url("+backgrounds[++current % backgrounds.length]+")" // no need to `current = `
    );
    setTimeout(nextBackground, 5000);
  }
  setTimeout(nextBackground, 5000);
  body.css("background-image", "url("+backgrounds[0]+")");
});

对于一个漂亮的淡入淡出EFX,你可以看一下我半天前回答的那个:Full screen slider with zoom in/out transition effect