如何在到达最后一张幻灯片后使滑块返回到第一张幻灯片,反之亦然

时间:2017-03-12 11:36:16

标签: javascript jquery css

我目前正在尝试自学javascript,现在我正在构建一个滑块。到目前为止,我已经设法弄清楚如何让滑块左右滑动。到目前为止我遇到的问题是如何在到达最后一张幻灯片后让滑块返回到第一张幻灯片,反之亦然。

这是我一直在努力的代码。



$(document).ready(function() {

  var totalSlides = $('.slides li').length,
    slidesWidth = $('.slides li').width(),
    slideContainer = $('.slides');
  slideCount = 0;
  slideItems = $('.slides li');

  slideContainer.width(slidesWidth * totalSlides);

  $('.buttons .next').on('click', function() {
    nextSlide();
  });

  $('.buttons .prev').on('click', function() {
    prevSlide();
  });

  function nextSlide() {
    slideCount++;
    if (slideCount <= totalSlides) {
      slideCount++;
      console.log(slideCount);
      slideItems.animate({
        left: '-=' + slidesWidth
      }, 200);
    } else if (slideCount === totalSlides) {
      slideCount = 0;
      slideItems.animate({
        left: '+=' + slideContainer
      }, 200);
    }
  }

  function prevSlide() {
    if (totalSlides >= slideCount) {
      slideCount--;
      console.log(slideCount);
      slideItems.animate({
        left: '+=' + slidesWidth
      }, 200);
    }
  }


  // function resetSlides() {
  //    if ( slideCount === totalSlides ) {
  //        slideCount = 0;
  //        slideItems.animate({
  //            left: '+=' + slideContainer
  //        }, 200);
  //    }
  // }
})
&#13;
.wrapper {
  max-width: 1440px;
  margin: 0 auto;
}

.timeline-container {
  max-width: 1440px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  height: 300px;
  .slides {
    position: absolute;
    background-color: #ccc;
    width: 1440px;
    max-height: 300px;
    top: 0;
    left: 0;
    li {
      float: left;
      max-width: 1440px;
      width: 100%;
      height: 300px;
      position: relative;
    }
  }
  .buttons {
    position: absolute;
    top: 50%;
    left: 0;
    z-index: 10;
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="timeline-container">
    <ul class="slides">
      <li>
        <div class="image">
        </div>
        <div class="content">
          1965
        </div>
      </li>
      <li>
        <div class="image">
        </div>
        <div class="content">
          1968
        </div>
      </li>
      <li>
        <div class="image">
        </div>

        <div class="content">
          1969
        </div>
      </li>
    </ul>
    <ul class="buttons">
      <li class="prev">&lt;</li>
      <li class="next">&gt;</li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

试试此代码

function gotoSlide(position){
if(position === 'first'){

    console.log(slideCount);
    slideItems.animate({
        left: '+=' + 0
    }, 200);
    slideCount=0;
}
else{
    console.log(slideCount);
    slideItems.animate({
        left: '+=' + slidesWidth*(totalSlides-1)
    }, 200);
    slideCount=totalSlides;
}
}

并点击按钮调用gotoSlide(yourPosition)。