Simple implementation carousel figure

Before writing hands, first to analyze

Here Insert Picture Description
You can see that there are two main ways to perform carousel figure, one is to switch the picture by the left button, one is to be switched by buttons on the right. Here we have to analyze the picture by switching to the right button.

  1. The right buttons
    First we define a variable index, when we click the button to the right time, index need to add 1. But the index can not be unlimited to increase, otherwise when our index exceeds carousel chart which put the number of the picture when it will not be switched, and get stuck in the last picture above. So, we then need to determine what index it is not greater than the maximum number, when it is greater than the maximum number of carousel figure, and its value is re-set to 0, so that you can achieve a switching cycle.
function bun(){
                index++;
                if(index>pic.length){
                    index=0;
                }

Then, it becomes easy for them, and when index + 1, we put the corresponding picture displayed through the display on it, to corresponding, we want to pass on a picture display: none to hide. that's it

pic[index].classList.add("show");
pic[index-1<0?4:index-1].classList.remove("show");

Above on the basic realization of the click of a button to switch the function the same way, the right button and the left button is the same, but change it parameters on it.

oLeft.onclick = function(){
            index--;
            if(index<pic.length){
                index=4;
            }
            pic[index].classList.add("show");
            pic[index+1>4?0:index-1].classList.remove("show");         
        }

It automatically cycle through the pictures, we just need to add a timer on it.

let swiper = setInterval(bun,3000);

Here is the complete code:

 let oLeft = document.querySelector(".left"),
            oRight = document.querySelector(".right"),
            pic = document.querySelectorAll(".b-img ul li"),
            txt = document.querySelectorAll(".b-tab ul li"),
            index=0;
        

            function bun(){
                index++;
                if(index>pic.Length){
                    index=0;
                }
                pic[index].classList.add("show");
                pic[index-1<0?4:index-1].classList.remove("show");
            }
        
        oRight.onclick=bun;

        oLeft.onclick = function(){
            index--;
            if(index<pic.Lenght){
                index=4;
            }
            pic[index].classList.add("show");
            pic[index+1>4?0:index-1].classList.remove("show");
        }

       let swiper = setInterval(bun,3000);

ok, you're done! Sahua (Effects below)
Here Insert Picture Description

Released two original articles · won praise 6 · views 574

Guess you like

Origin blog.csdn.net/HeartzzZZ/article/details/105082341