fadeIn更改backgroundImage jQuery

时间:2018-07-18 05:29:19

标签: javascript jquery

我有此代码:

<script>
    var images = [
      "images/achtergronden/bg1.png",
      "images/achtergronden/bg2.png",
      "images/achtergronden/bg3.png",
      "images/achtergronden/bg4.png"
    ]
  $(document).ready(function(){
    var i = 0;
    setInterval(function() {
          document.body.style.backgroundImage = "url(" + images[i] + ")";
          i = i + 1;
          if (i == images.length) {
            i =  0;
          }
    }, 5000);
   });
</script>

现在,我希望背景图像渐入渐出。这可能吗?

2 个答案:

答案 0 :(得分:0)

是的,这是可能的:-

             var images = [
   "https://cdn.pixabay.com/photo/2018/06/23/16/22/romanesco-3493007_960_720.jpg",
    "https://cdn.pixabay.com/photo/2015/01/28/23/35/landscape-615429_960_720.jpg",
    "https://cdn.pixabay.com/photo/2012/08/27/14/19/evening-55067_960_720.png",
    "https://cdn.pixabay.com/photo/2012/03/01/00/21/bridge-19513_960_720.jpg"
        ]
  $(document).ready(function(){
  var i = 0;
    setInterval(function() {
		 $('#imageDiv').fadeOut("slow",
		 function(){
          imageDiv.style.backgroundImage = "url(" + images[i] + ")";
          i = i + 1;
          if (i == images.length) {
            i =  0;
          }
		   $('#imageDiv').fadeIn("slow")
		 });
	},5000);
      });
#imageDiv{ width:500px; height:300px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="imageDiv"></div>

答案 1 :(得分:0)

也许您可以尝试以下方式:

$(document).ready(function(){
  var images = [
  "https://images.pexels.com/photos/54630/japanese-cherry-trees-flowers-spring-japanese-flowering-cherry-54630.jpeg?auto=compress&cs=tinysrgb&h=350",
  "https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg?auto=compress&cs=tinysrgb&h=350",
  "https://images.pexels.com/photos/70069/pexels-photo-70069.jpeg?auto=compress&cs=tinysrgb&h=350",
  "https://images.pexels.com/photos/46231/water-lilies-pink-water-lake-46231.jpeg?auto=compress&cs=tinysrgb&h=350"
  ]
  images.forEach(function(img){
    $('.container').append('<img src="'+img+'"/>');
  });

  var images = $('.container > img');
  images.first().addClass('active');

  setInterval(function() {
      var current = images.filter('.active');    
      current.removeClass('active');
      var next = ( current.next().length ? current.next() : images.eq(0) );
      next.addClass('active');    
  }, 5000);
});
.container > img {
  opacity: 0;
  position: absolute;
   -webkit-transition: all 1s linear;
  transition: all 5s linear;
}

.container > img.active {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container"></div>