如何使Javascript淡出滑动背景?

时间:2014-05-26 17:13:33

标签: javascript jquery html css

我正在研究一些最后的校园项目,但我一直在搞乱我想用作背景的图像滑块。

它起作用了,但是没有特效让慢慢消失。

你能为我的问题建议一个解决方案吗?

到目前为止我的代码:

<script  type="text/javascript">
    var images = new Array();
    images[0] = "img/bck.png";
    images[1] = "img/bck2.png";
    images[2] = "img/bck3.png";
    images[3] = "img/bck4.png";
    images[4] = "img/bck5.png";

    window.onload = function showDelay() {
        setInterval ("changeBg()", 3000);
    }

    var i=0;
    function changeBg() {
        if (i==5) {
            i=0;
        }
        document.body.style.backgroundImage = 'url('+images[i]+')';
        i++;
    }
</script>

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery实现相同的功能。

工作示例 - http://codepen.io/nitishdhar/pen/fhjkD

代码设置&amp;说明

像这样设置你的HTML -

<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
 <div class="bg-holder">
   <img class="fade" src="http://placehold.it/940x800/DF013A">
   <img class="fade" src="http://placehold.it/940x800/A901DB">
   <img class="fade" src="http://placehold.it/940x800/013ADF">
 </div>
</body>
</html>

创建一个div,其中包含您要使用的所有背景图像。

添加一些CSS -

.bg-holder {
  position: fixed;
  z-index: -1; 
  top: 0; 
  left: 0; 
  background-color: #000;
}
.bg-holder img.fade {
  position: absolute;
  top: 0;
  display: none;
  width: 100%;
  height: 100%;
  z-index: -1;
}

然后添加一些jQuery代码,别忘了在头脑中使用include jQuery库 -

function setupBackgroundAnimation() {
  $('img.fade').hide();
  $('.bg-holder').css({ 'height': $(window).height(),'width': $(window).width() });
  animateBackground();
}

function animateBackground() {
  $(".bg-holder img.fade").first().appendTo('.bg-holder').fadeOut(1500);
  $(".bg-holder img").first().fadeIn(1500);
  setTimeout(animateBackground, 3000);
}

/*Initiate Animated Background on Document Ready*/
$(document).ready(function() {
   setupBackgroundAnimation();
});

animateBackground函数保存bg-holder div&amp;中的第一个图像。淡出它时将它移到最后。然后通过淡入淡出来显示下一个图像。每3000毫秒重复一次(在将当前图像淡出时为1500毫秒,在下一张图像中为淡入淡出为1500)

setupBackgroundAnimation函数调整bg-holder的大小以适应当前窗口大小。

答案 1 :(得分:-1)

!function( global, doc ){

 var images = ["img/bck.png", "img/bck2.png", "img/bck3.png" /* ... */ ]
  , i = 0;

 global['onload'] = function() {
  setInterval (function(){
    i === 5 && (i = 0);
     doc.body.style.backgroundImage = 'url(' + images[i] + ')';
    i++;
    }, 3000);
  }

 }(window, document)
相关问题