FadeIn() images in slideshow using jquery

孤人 提交于 2019-12-01 13:23:06

I'd recommend something like this for your interval function:

window.setInterval(function (){
  var images = $('#backgroundChanger img');
  var active, next;

  images.each(function(index, img) {
    if($(img).hasClass('active')) {
      active = index;
      next = (index === images.length - 1) ? 0 : index + 1;
    }
  });

  $(images[active]).fadeOut(1000, function() {
    $(images[next]).fadeIn(1000);
  });

  $(images[next]).addClass('active');
  $(images[active]).removeClass('active');
}, 3000);

And this is all you'd need for your css:

#backgroundChanger img:first-child {
  display: block;
}

#backgroundChanger img {
  display: none;
}

And keep the same HTML and you should be good to go!

You can fadeIn() the next image in the callback of fadeOut() as shown below:

$(window).load(function() {
  var $slider = $("#backgroundChanger"),
    $slides = $slider.find("img"),
    $firstSlide = $slides.first();

  function cycleImages() {
    var $active = $('#backgroundChanger .active'),
      $next = ($active.next().length > 0) ? $active.next() : $firstSlide;
    $active.fadeOut(1000, function() {
      $active.removeClass('active');
      $next.fadeIn(1000).addClass('active');
    });
  }

  setInterval(cycleImages, 3000);
})
#backgroundChanger img {
  position: absolute;
  width: 150px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="backgroundChanger">
  <img class="active" src="http://i46.tinypic.com/2epim8j.jpg" />
  <img src="http://i49.tinypic.com/28vepvr.jpg" />
  <img src="http://i50.tinypic.com/f0ud01.jpg" />
</div>

Notes:

  • Since we're dealing with images, It's better to use load() handler than ready() to make sure the slide show starts after the images are loaded
  • You can slightly improve the performance by caching the elements accessed frequently
  • You don't have to play with z-index property at all since both fadeIn() and fadeOut() changes the elements `display property itself
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!