使用setinterval的jquery淡入淡出循环

时间:2015-08-07 12:19:15

标签: jquery slideshow setinterval fadein

我正在尝试基于CSS-tricks Auto-Playing Slideshow创建自己的简单淡入淡出循环。我需要允许页面中有多个可能。

出于某种原因,我的幻灯片不会超过第二个幻灯片。也许是因为把它放在一个函数中?

$('.jCaroFade').each(createFader);
function createFader (i, elem) {
    var track = $(elem);
    var firstSlide = track.find('.slide').eq(0);

    firstSlide.nextAll().hide();
    setInterval(function() { 
      firstSlide
      .fadeOut(500)
      .next()
      .fadeIn(500)
      .end()
      .appendTo(track);
    },  3000);

}

小提琴:https://jsfiddle.net/L66v8oxv/

谢谢!

1 个答案:

答案 0 :(得分:2)

您没有更改firstSlide参考

$('.jCaroFade').each(createFader);

function createFader(i, elem) {
  var track = $(elem);
  var firstSlide = track.find('.slide').eq(0);
  var loop = 0;

  firstSlide.nextAll().hide();
  setInterval(function() {
    loop++;
    firstSlide = firstSlide.fadeOut(500, function() {
        $(this).appendTo(track);
      })
      .next()
      .fadeIn(500);
  }, 3000);

}
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  font-family: sans;
}
.track {
  position: relative;
  height: 400px;
  width: 100%;
}
.slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
.ipsum {
  display: inline-block;
  padding: 10px;
  background-color: rgba(255, 255, 255, .75);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="jCaroFade track">
  <!-- Slides -->
  <div class="slide" style="background-image:url('https://c1.staticflickr.com/1/550/20180902929_88c507f552_h.jpg');">
    <p class="ipsum">SLIDE ONE</p>
  </div>
  <div class="slide" style="background-image:url('https://c1.staticflickr.com/1/277/19726574813_cf2aa22221_b.jpg');">
    <p class="ipsum">SLIDE TWO</p>
  </div>
  <div class="slide" style="background-image:url('https://c1.staticflickr.com/1/488/20178281609_c1e34be0b2_b.jpg');">
    <p class="ipsum">SLIDE THREE</p>
  </div>
  <div class="slide" style="background-image:url('https://c1.staticflickr.com/1/414/19744665244_c099ce816c_h.jpg');">
    <p class="ipsum">SLIDE FOUR</p>
  </div>
</div>