js to achieve sliding carousel effect

js to achieve sliding carousel effect

This article shares the specific code of js to achieve the sliding carousel effect for your reference. The specific content is as follows

1. Build the HTML style, the code is as follows

<div class="banner">
        <ul>
            <li>
                <a href="#" >
                    <img src="images/1.jpeg">
                </a>
            </li>
            <li>
                <a href="#" >
                    <img src="./images/2.jpg">
                </a>
            </li>
            <li>
                <a href="#" >
                    <img src="./images/3.jpg">
                </a>
            </li>
            <li>
                <a href="#" >
                    <img src="./images/4.jpg">
                </a>
            </li>
            <li>
                <a href="#" >
                    <img src="./images/5.jpg">
                </a>
            </li>
        </ul>
        <ol>
            
        </ol>
        <a href="#" class="left">&lt;</a>
        <a href="#" class="right">&gt;</a>
</div>

2. Understand the basic structure of HTML. You can create your own path for the picture and simply modify the HTML structure with CSS style. The code is as follows

<style>
    *{
        padding: 0;
        margin: 0;
        list-style: none;
        text-decoration: none;
        color:#000;
    }
    .banner{
        width: 500px;
        height: 300px;
        margin:50px auto;
        position: relative;
        border:1px solid #000;
        overflow:hidden;
    }
    .banner ul{
        position: absolute;
        left: 0;
        top: 0;
        height: 300px;
        /* width: 2500px; */
    }
    .banner ul li{
        width: 500px;
        height: 300px;
        float:left;
    }
    .banner ul li a img{
        width: 500px;
        height: 300px;
    }
    .banner ol{
        /* width: 100px; */
        height: 20px;
        position:absolute;
        bottom:10px;
        background-color: rgba(255,255,255,.7);
        left:50%;
        transform: translateX(-50%);
        border-radius:10px;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
    }
    /* .banner ol li{
        width: 10px;
        height: 10px;
        border-radius:50%;
        background-color: skyblue;
    } */
    .banner>a{
        width: 20px;
        height: 40px;
        position:absolute;
        top:50%;
        transform: translateY(-50%);
        background-color: rgba(10,10,10,.5);
        font-size:20px;
        color:#fff;
        line-height: 2;
        text-align: center;
    }
    .banner>a.left{
        left: 0;
    }
    .banner>a.right{
        right: 0;
    }

3. After the basic layout is completed, use js to implement the carousel. The code is as follows

var div = document.querySelector('.banner');
var ul = document.querySelector('ul');
var ol = document.querySelector('ol');
var left = document.querySelector('a.left');
var right = document.querySelector('a.right');
    // Set a variable index to use as the subscript var index = 1;
    // Traverse the li below ul
for(var i=0;i<ul.children.length;i++){
    // Each li under a ul should correspond to a small dot button below // Create the same number of small dots var li = document.createElement('li');
    setStyle(li,{
        width: "10px",
        height: "10px",
        "border-radius":"50%",
        "background-color": "skyblue"
    })
    // Put all created li into the big box ol.appendChild(li);
}
    // The ol box itself has no width. We need to set the width of the ol box according to the number of small dots inside. ol.style.width = ol.firstElementChild.offsetWidth*ul.children.length*2 + 'px';
    // Set a variable that represents the dot with style var that = ol.children[index-1];
//Set the color red for the first son of ol that.style.background = 'red';
// To achieve better connection between sliding carousel, add a li before and after ul.
var lastLi = ul.lastElementChild.cloneNode(true);
var firstLi = ul.firstElementChild.cloneNode(true);
// Place the copied labels in front and behind the ul box ul.appendChild(firstLi);
ul.insertBefore(lastLi,ul.firstElementChild);
// Because the child elements under ul have changed, we need to set the corresponding width for ul ul.style.width = ul.children.length*lastLi.offsetWidth + 'px';
// Because we slide from right to left, we need to negative the left value of ul ul.style.left = -ul.firstElementChild.offsetWidth + 'px';
// Set the variable and assign it to the timer var timeId;
// Define a switch var flag = true;
//Right click right.onclick = function(){
    // If the switch is not on, return false
    if(!flag){
        return false;
    }
    // And assign the return value to the switch to indicate that if the switch is closed, clicking it again will have no effect flag = false;
    // Earlier we defined an index and every time we click on it, index++
    index++;
    // Call move function move(ul,{left:-index*ul.children[0].offsetWidth},function(){
        // Put what needs to be done in the function after the exercise is completed // First, we need to judge the index. There are a total of seven child elements in ul. The index corresponds to the subscript of the ul child element, so the index cannot exceed ul.children.length-1;
        if(index == ul.children.length - 1){
            // If index is equal to ul.children.length-1
            // Reassign index to 1
            index = 1;
            // And also reassign the left value of ul ul.style.left = -index*ul.children[0].offsetWidth + 'px';
        }
        // The dot must also move with the image // We set the dot corresponding to the image to the variable that because the dot itself has a style, first set its style to the default that.style.backgroundColor = 'skyblue';
        // The style of the corresponding small dot has changed ol.children[index-1].style.backgroundColor = 'red';
        // After the style conversion is successful, assign the dot containing the style to the variable that
        that = ol.children[index-1];
        // At the end of the movement, turn on the switch so that you can right-click to turn it on again flag = true;
    })
}
//Left click left.onclick = function(){
    if(!flag){
        return false;
    }
    flag = false;
    // Left click is sliding from left to right and becomes index--
    index--;
    move(ul,{left:-index*ul.children[0].offsetWidth},function(){
        if(index == ul.children.length - 1){
            index = 1;
            ul.style.left = -index*ul.children[0].offsetWidth + 'px';
        }
         //After entering the event, first determine the value of index if(index==0){
            // If the value of index becomes 0, reassign index index = ul.children.length-2;
            // And reassign the left value of ul to the value of the second picture ul.style.left = -index * firstLi.offsetWidth + "px"
        }
        that.style.backgroundColor = 'skyblue';
        ol.children[index-1].style.backgroundColor = 'red';
        that = ol.children[index-1];
        flag = true;
    })
}
// Traverse all li under ol
for(let i=0;i<ol.children.length;i++){
    // Click on the small dot event ol.children[i].onclick = function(){
    if(!flag){
        return false;
    }
    flag = false;
    // Because the bottom of the dot is 1 less than the subscript of the image, we need to reassign the index in the dot click event // so that the dot and the image can correspond to index = i+1;
    move(ul,{left:-index*firstLi.offsetWidth},function(){
            // if(index == 0){
            // index = ul.children.length - 2
            // ul.style.left = -index.ul.children[0].offsetWidth + 'px'
            // }
            that.style.backgroundColor = 'skyblue';
            ol.children[index-1].style.backgroundColor = 'red';
            that = ol.children[index-1];
            flag = true;
        })
    }
};
    // Automatic rotation timeId = setInterval(function(){
        if(!flag){
            return false;
        }
        flag = false;
        index++;
        move(ul,{left:-index*firstLi.offsetWidth},function(){
            if(index == ul.children.length - 1){
                index = 1
                ul.style.left = -index*ul.children[0].offsetWidth + 'px'
            }
            that.style.backgroundColor = 'skyblue';
            ol.children[index-1].style.backgroundColor = 'red';
            that = ol.children[index-1];
            flag = true;
        })
    },2000);

    // Stop the carousel when the mouse passes over itdiv.onmouseover = function(){
        clearInterval(timeId);
    }

    //Automatically rotate after the mouse leaves div.onmouseout = function(){
        timeId = setInterval(function(){
            if(!flag){
                return false;
            }
            flag = false;
            index++;
            move(ul,{left:-index*firstLi.offsetWidth},function(){
                if(index == ul.children.length - 1){
                    index = 1
                    ul.style.left = -index*ul.children[0].offsetWidth + 'px'
                }
                that.style.backgroundColor = 'skyblue';
                ol.children[index-1].style.backgroundColor = 'red';
                that = ol.children[index-1];
                flag = true;
            })
        },1000);
    };
//Packaged multi-motion function function move(ele,obj,fn){
            let timeObj = {};
            for(let attr in obj){
                timeObj[attr] = setInterval(function(){
                    var target = parseFloat(obj[attr]);
                    if (attr === 'opacity') {
                        target*=100
                    }
                    var t = parseFloat(getStyle(ele,attr));
                    if (attr === 'opacity') {
                        t*=100
                    }
                    console.log(t)
                    if((target-t)/100>0){
                        var percent = Math.ceil((target-t)/100);
                    }else{
                        var percent = Math.floor((target-t)/100);
                    }
                    t += percent;
                    if (attr === 'opacity') {
                        ele.style[attr] = t/100 
                    }else{
                        ele.style[attr] = t + 'px';
                    }
                    if(t == target){
                        clearInterval(timeObj[attr])
                        delete timeObj[attr]
                        let k = 0;
                        for(let i in timeObj){
                            k++;
                        }
                        if( k==0){
                            fn();
                            console.log(123)
                        }
                    }
                },10)
            }
        }

// Encapsulated function to get style function getStyle(ele,attr){
    if (window.getComputedStyle) {
        return window.getComputedStyle(ele)[attr];
    }else{
        return ele.currentStyle[attr];
    }
}
// Encapsulate the function of setting style function setStyle(ele,styleObj){
    for(var attr in styleObj){
        ele.style[attr] = styleObj[attr];
    }
};

4. The pictures needed for the carousel are as follows

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js to achieve mobile carousel sliding switch
  • Native js sliding carousel encapsulation
  • Native JS seamless sliding carousel
  • An example of using js to natively implement the finger sliding carousel effect on mobile devices
  • js realizes the sliding carousel effect from left to right
  • JS realizes automatic carousel effect (adaptive screen width + mobile phone touch screen sliding)
  • JS implements touch click sliding carousel example code
  • js to achieve fixed width and height sliding carousel effect
  • js to achieve the effect of supporting mobile phone sliding switch carousel picture example
  • Native js to realize mobile development carousel and album sliding effects

<<:  Use of Linux gzip command

>>:  Mysql table creation foreign key error solution

Recommend

Summary of Vue first screen performance optimization component knowledge points

Vue first screen performance optimization compone...

Detailed explanation of Vue's keyboard events

Table of contents Common key aliases Key without ...

Nginx location matching rule example

1. Grammar location [=|~|~*|^~|@] /uri/ { ... } 2...

Detailed explanation of Mysql communication protocol

1.Mysql connection method To understand the MySQL...

Vue.js implements the nine-grid image display module

I used Vue.js to make a nine-grid image display m...

Detailed explanation of using Vue.prototype in Vue

Table of contents 1. Basic Example 2. Set the sco...

Summary of JavaScript JSON.stringify() usage

Table of contents 1. Usage 1. Basic usage 2. The ...

Docker volume deletion operation

prune To use this command, both the client and da...

How to query the minimum available id value in the Mysql table

Today, when I was looking at the laboratory proje...

HTML web page image tag

Insert image tag <IMG> The colorful web page...

Vue plugin error: Vue.js is detected on this page. Problem solved

Vue plugin reports an error: Vue.js is detected o...

Understand all aspects of HTTP Headers with pictures and text

What are HTTP Headers HTTP is an abbreviation of ...

The implementation principle of Tomcat correcting the JDK native thread pool bug

To improve processing power and concurrency, Web ...

ReactRouter implementation

ReactRouter implementation ReactRouter is the cor...

How to deploy Go web applications using Docker

Table of contents Why do we need Docker? Docker d...