[This article is enough to learn carousel pictures] JS web page carousel picture detailed automatic playback + manual playback

Carousel pictures have become an indispensable part of page development. Carousel pictures can be seen everywhere in daily life, such as Taobao, JD.com, etc., which rely on carousel pictures in a limited area. More items are displayed inside. This is also the earliest hand-practice project that front-end programmers have come into contact with. This article will take you through the carousel map! No longer confused

 First, let's take a look at the effect of this case:

(The following is asking my girlfriend to leave the country! In other words, I don't understand how to set the gif image, but in short, there are functions that should be there, and functions that should not be there (such as killing dogs hhhhh), autoplay, click the switch button Switching pictures, click the dots below to switch pictures can be achieved, I will not demonstrate them one by one, the main thing is to let everyone understand what the principle is)

I'll break it down into the following steps :

  1. Basic structure construction and principle analysis of carousel map
  2. Move the cursor to the display and hide the toggle button at the carousel
  3. Click the button below to switch the realization of the picture
  4. The scrolling of the right button and the synchronous change of the points below
  5. The scrolling implementation of the left button and the synchronous change of the points below
  6. Autoplay implementation

1: Basic structure construction and principle analysis of carousel map

In fact, the composition of the carousel is very simple. It only consists of two parts: the display area and the picture area. The picture area is realized by a ul tag, and a picture is placed in a li tag inside, so that it floats to the left to form a line, and its movement actually depends on It is the animation principle of ul to   move left and right to change the display area, the effect is as follows: (HTML and CSS of the page structure, and the encapsulated animation function js file at the end of the article)


Two: Move the cursor to the display and hide the toggle button at the carousel

 The cursor moves to the carousel area to display and hide the left and right switching picture buttons. We use two events:  mouseenter  and mouseleave . The reason why mouseover and mouseout are not used is because these two events will bubble and cause a lot of uncontrollable events. , but the effects of the two groups of events were almost identical. Change the display value of the button after binding the event.

First of all, let's understand what elements are obtained, so as to avoid doubts in the following step-by-step explanation:

    var leftbtn=document.querySelector('.leftbtn');   //左按钮
    var rightbtn=document.querySelector('.rightbtn');  //右按钮
    var windows=document.querySelector('.windows');  //显示窗口区域
    var circleul=document.querySelector('.imgbox');  //装图片的 ul
    var circleol=document.querySelector('.circle');  //装下方小点点的 ol

This part is  the implementation of the display and hide of the toggle button where the cursor moves to the carousel :

  windows.addEventListener('mouseenter',function(){
        leftbtn.style.display='block';
        rightbtn.style.display='block';
        clearInterval(timer)    //清除定时器自动播放,此处不需要管
        timer=null;
    })
    windows.addEventListener('mouseleave',function(){
        leftbtn.style.display='none'
        rightbtn.style.display='none'
        timer=setInterval(function(){
            rightbtn.click();
        },2000)
    })
    leftbtn.addEventListener('click',function(){  //按钮点击后变色一下的效果
        leftbtn.style.color='grey'
        var timer=setTimeout(function(){
            leftbtn.style.color='aliceblue'
        },100)
    })
    rightbtn.addEventListener('click',function(){
        rightbtn.style.color='grey'
        var timer=setTimeout(function(){
           rightbtn.style.color='aliceblue'
        },100)
    })

 Three: Click the button below to switch the realization of the picture

The function of the for loop is to add the number of small dots in the ol according to the number of pictures in the ul and add them to the ol , add a custom attribute index to the created li , and the i of the for  loop is used as the attribute value of each li , and As the child nodes of ul, the picture corresponds to children[0], children[1], children[2], children[3] , which is exactly one-to-one correspondence with the index of the custom attribute, that is to say, each point is paired with the same serial number picture.

When adding each li , bind the click event to each li , get the custom attribute index, use the exclusive idea to change the color of the clicked origin, and call the encapsulated animation function to complete the click of the small dot switch The effect of the picture

 These two lines are the key code for moving: windows.offsetWidt is used to get the width of each picture, -6 is to eliminate the error caused by the interval between pictures in some movements

var imgwidth=windows.offsetWidth-6;
var long=this.getAttribute('index')*imgwidth;

Click on the first little dot:

 Click on the second little dot:

 Click on the third little dot:

Code:

 for(var i=0;i<circleul.children.length;i++){   //根据图片个数自动创建小点点个数
        lis=document.createElement('li');
        lis.setAttribute('index',i);
        circleol.appendChild(lis);
        lis.addEventListener('click',function(){
            var currentindex=this.getAttribute('index'); //bug整改
            num=currentindex;  //bug整改
            circlechange=currentindex;  //bug整改
            for(var i=0;i<circleol.children.length;i++){  //排他思想
                circleol.children[i].className='';
            }
            this.className='circlecolor';
            var imgwidth=windows.offsetWidth-6;
            var long=this.getAttribute('index')*imgwidth;
            run(circleul,-long);  //封装好的动画函数
        })
    }

 4: The scrolling of the right button and the synchronous change of the points below

Finally, a key step has been reached. The movement of the carousel through buttons is also the most abstract part of this case. The abstraction is the seamless connection between the last image and the first image. Here we will explain what we want to make seamless The principle is to put a clone of the first picture behind the last picture (the dots below do not include the cloned picture, but the sub-element of ul contains this new cloned picture!) , scroll the picture After arriving at the cloned image, immediately change the left value of its ul to 0.

To clone the first image we use a parameterized clone of the node:

var firstimg=circleul.children[0].cloneNode(true);
circleul.appendChild(firstimg);

We already know that the scrolling distance of the picture is equal to the order of the picture multiplied by the width of the picture. Here we first set a global variable num, and set the initial value to 0. Click the right button once and num will increase by 1. Click num for the first time. Auto-increment 1, num=1, the moving distance is 1✖ width, the second click on num increases by 1, num=2, the moving distance is 2✖ width, the previous steps are easy to understand, but when num is the last seamless connection When a judgment statement is needed, we focus on the principle of seamless connection: 

After clicking the right button for the first time: 

 After clicking the right button a second time:

 After clicking the right button for the third time:

After clicking the right button for the fourth time:

Note that num=3 before the judgment in this step, that is, the statement in the judgment will not be executed, but after the judgment, the num will automatically increase to 4, which means that the statement in the judgment will be executed next time.

 After the fifth click on the right button:

Why did I click directly to the second picture? Isn't left set to 0 in the judgment statement? This is because num=0 and left=0 are set in the judgment, and 1 is automatically incremented, so this time, after the click, the num=1 of the animation function is brought into the animation function, and the moving distance is 1✖ width, and a new cycle of pictures is started!

Code:

    num=0;
    circlechange=0;  //目的为下方点点同步改变时使用,这一步先不用管这个参数
    rightbtn.addEventListener('click',function(){
        if(num==circleul.children.length-1){
            circleul.style.left=0;
            num=0;
        }
        num++;
        long=num*windows.offsetWidth-6*num;
        run(circleul,-long);

When we click the button on the right, the small circle should also switch while the picture is scrolling. How to achieve it?

Every time you click, let the variable circlechange increment automatically. When the value of the increment is equal to the value of circleul.children.length-1 (that is, scroll to the last image in the cloned past), then let circlechange become 0.

  circlechange++;
        if(circlechange==circleul.children.length-1){
           circlechange=0;
        }
        for(var i=0;i<circleol.children.length;i++){  //排他思想
             circleol.children[i].className='';
        }
        circleol.children[circlechange].className='circlecolor';
    })

Five: The scrolling implementation of the left button and the synchronous change of the lower points 

The principle of switching to the left and switching to the right is similar. Here we only study the process of seamlessly connecting the last image to the left from the first image.

After clicking the left button for the first time:

Code: 

 leftbtn.addEventListener('click',function(){
        if(num==0){
            circleul.style.left=(circleul.children.length-1)*windows.offsetWidth;
            num=circleul.children.length-1;
        }
        num--;
        long=num*windows.offsetWidth-6*num;
        run(circleul,-long);

 Click the button on the left, and the small circle will follow the switch:

 circlechange--;
        if(circlechange<0){
           circlechange=circleol.children.length-1;  //注意此处是ol的子节点的长度-1
        }
        for(var i=0;i<circleol.children.length;i++){
             circleol.children[i].className='';
        }
        circleol.children[circlechange].className='circlecolor';
    })

Six: automatic playback implementation

Autoplay is the easiest! , with just one automatic click

Here is the automatic click of the right button: rightbtn.click()

Add it to the timer to complete our carousel

 var timer=setInterval(function(){
            rightbtn.click();
        },2000)

Complete JS code:

Our JS is a separate file, so after adding the load event and other document flow execution, execute the content of JS

window.addEventListener('load',function(){
    var leftbtn=document.querySelector('.leftbtn');
    var rightbtn=document.querySelector('.rightbtn');
    var windows=document.querySelector('.windows');
    var circleul=document.querySelector('.imgbox');
    var circleol=document.querySelector('.circle');
    //光标移动至轮播图区域按钮显示,移开隐藏,点击按钮的变化效果
    windows.addEventListener('mouseenter',function(){
        leftbtn.style.display='block';
        rightbtn.style.display='block';
        clearInterval(timer)//清除定时器自动播放
        timer=null;
    })
    windows.addEventListener('mouseleave',function(){
        leftbtn.style.display='none'
        rightbtn.style.display='none'
        timer=setInterval(function(){
            rightbtn.click();
        },2000)
    })
    leftbtn.addEventListener('click',function(){
        leftbtn.style.color='grey'
        var timer=setTimeout(function(){
            leftbtn.style.color='aliceblue'
        },100)
    })
    rightbtn.addEventListener('click',function(){
        rightbtn.style.color='grey'
        var timer=setTimeout(function(){
           rightbtn.style.color='aliceblue'
        },100)
    })
    //点击小圆圈可以滚动
    for(var i=0;i<circleul.children.length;i++){
        lis=document.createElement('li');
        lis.setAttribute('index',i);
        circleol.appendChild(lis);
        lis.addEventListener('click',function(){
            var currentindex=this.getAttribute('index');//bug整改(3行)
            num=currentindex;
            circlechange=currentindex;
            for(var i=0;i<circleol.children.length;i++){
                circleol.children[i].className='';
            }
            this.className='circlecolor';
            var imgwidth=windows.offsetWidth-6;
            var long=this.getAttribute('index')*imgwidth;
            run(circleul,-long);
        })
    }
    circleol.children[0].className='circlecolor';
    //克隆第一张图片至末尾
    var firstimg=circleul.children[0].cloneNode(true);
    circleul.appendChild(firstimg);

//右侧按钮点击滚动
    num=0;
    circlechange=0;
    rightbtn.addEventListener('click',function(){
        if(num==circleul.children.length-1){
            circleul.style.left=0;
            num=0;
        }
        num++;
        long=num*windows.offsetWidth-6*num;
        run(circleul,-long);
    //小圆圈跟着一起变化
        circlechange++;
        if(circlechange==circleul.children.length-1){
           circlechange=0;
        }
        for(var i=0;i<circleol.children.length;i++){
             circleol.children[i].className='';
        }
        circleol.children[circlechange].className='circlecolor';
    })
    //左侧按钮滚动
    leftbtn.addEventListener('click',function(){
        if(num==0){
            circleul.style.left=(circleul.children.length-1)*windows.offsetWidth;
            num=circleul.children.length-1;
        }
        num--;
        long=num*windows.offsetWidth-6*num;
        run(circleul,-long);
    //小圆圈跟着一起变化
        circlechange--;
        if(circlechange<0){
           circlechange=circleol.children.length-1;  //注意此处是ol的子节点的长度-1
        }
        for(var i=0;i<circleol.children.length;i++){
             circleol.children[i].className='';
        }
        circleol.children[circlechange].className='circlecolor';
    })
   //自动播放
        var timer=setInterval(function(){
            rightbtn.click();
        },2000)

})

Animation function code:


    function run(obj,long,callback){
        clearInterval(obj.timer)
        obj.timer=setInterval(function(){
            if(obj.offsetLeft==long){
                window.clearInterval(obj.timer);
                if(callback){
                    callback();
                }
            }else{
                step=(long-obj.offsetLeft)/10
                step=step>0?Math.ceil(step):Math.floor(step)
                obj.style.left=obj.offsetLeft+step+'px';
            }
        },20)
    }

 

HTML+CSS complete code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .windows{
            position: relative;
            border: 3px rgb(146, 146, 146) solid;
            width: 700px;
            height: 450px;
            background-color: rgb(250, 186, 186);
            margin: 170px auto;
            overflow: hidden;
        }
        .leftbtn{
            z-index: 999;
             position: absolute;
             box-sizing: border-box;
             top: 195px;
             left: 0;
             width: 50px;
             height: 70px;
             background-color: rgba(136, 135, 135, 0.582);
             line-height: 70px;
             text-align: center;
             font-size: 35px;
             color: rgba(255, 255, 255, 0.609);
             cursor: pointer;
             display: none;
        }
        .leftbtn:hover{
            background-color: rgba(189, 186, 186, 0.623);
            color: aliceblue;
        }
        .rightbtn{
            z-index: 999;
             position: absolute;
             box-sizing: border-box;
             top: 195px;
             right: 0;
             width: 50px;
             height: 70px;
             background-color: rgba(136, 135, 135, 0.609);
             line-height: 70px;
             text-align: center;
             font-size: 35px;
             color: rgba(255, 255, 255, 0.596);
             cursor: pointer;
             display: none;
        }
        .rightbtn:hover{
            background-color: rgba(189, 186, 186, 0.623);
            color: aliceblue;
        }
        .imgbox{
           position:absolute;
           left: 0;
           top: 0;
            box-sizing: border-box;
            width: 700%;
            height: 450px;
        }
        .imgbox li{
            float: left;
            box-sizing: border-box;
            width: 700px;
            height: 450px;
            list-style: none;
        }
        .imgbox li a{
            box-sizing: border-box;
            display: inline-block;
            width: 700px;
            height: 450px;
            background-color: rgb(134, 152, 255);
        }
        .imgbox li a img{
            cursor:auto;
            width: 700px;
            height: 450px;
        }
        .circlebox{
            position: absolute;
            bottom: 0;
            width: 700px;
            height: 40px;
            background-color: rgba(94, 94, 94, 0.486);

        }
        .circle {
            position: absolute;
            bottom: 10px;
            left: 300px;
        }
        .circle li {
            float: left;
            width: 7px;
            height: 7px;
            list-style: none;
            border: 2px solid rgb(185, 185, 185);
            border-radius:100%;
            margin: 3px;
            cursor: pointer;
            background-color: rgb(173, 173, 173);
        }
        .circlecolor{
            background-color: coral !important;
            border: 2px solid coral !important;
        }
    </style>
    <script src="../js/run.js"></script>
    <script src="../js/btn-display.js"></script>
</head>
<body>
    <div class="windows">
        <div class="leftbtn"> < </div>
        <div class="rightbtn"> > </div>
        <ul class="imgbox">
            <li>
                <a href="#"><img src="../轮播photo/1.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
            <li>
                <a href="#"><img src="../轮播photo/2.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
            <li>
                <a href="#"><img src="../轮播photo/3.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
            <li>
                <a href="#"><img src="../轮播photo/4.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
            <li>
                <a href="#"><img src="../轮播photo/5.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
            <li>
                <a href="#"><img src="../轮播photo/6.jpg" alt="轮播图" class="lunboimg"></a>
            </li>
        </ul>
        <div class="circlebox">
               <ol class="circle"></ol>
        </div>
      
     
       
    </div>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123823438