[英]How can I make the slider go back to the first slide after reaching the last slide and vice versa
I'm currently trying to teach to myself javascript and right now I'm in the middle of building a slider. 我目前正在尝试自学JavaScript,现在正在构建滑块。 So far I've to managed to figure out how I can make slider slide left and right.
到目前为止,我已经设法弄清楚了如何使滑块左右滑动。 My problems so far at the monent is how can I make slider go back to the first slide after reaching the last slide and vice versa.
到目前为止,我在问题上遇到的问题是,在到达最后一张幻灯片后如何使滑块回到第一张幻灯片,反之亦然。
Here is a code I have been working on. 这是我一直在努力的代码。
$(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); // } // } })
.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; } }
<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"><</li> <li class="next">></li> </ul> </div> </div>
Try this code 试试这个代码
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;
}
}
and call gotoSlide(yourPosition) on the button click. 并在单击按钮时调用gotoSlide(yourPosition)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.