简体   繁体   中英

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. 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">&lt;</li> <li class="next">&gt;</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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM