JavaScript to achieve fancy carousel effect

JavaScript to achieve fancy carousel effect

This article shares two methods of implementing the fancy carousel effect with JavaScript for your reference. The specific contents are as follows

The first one: a simple carousel with buttons

Introduction: The left and right buttons control the carousel. Click the left button to switch to the previous picture, and click the right button to switch to the next picture.

The html is as follows:

<div class="box">
        <div class="imgbox">
            <a><img src="img/banner1.jpg" alt=""></a>
            <a><img src="img/banner2.jpg" alt=""></a>
            <a><img src="img/banner3.jpg" alt=""></a>
            <a><img src="img/banner4.jpg" alt=""></a>
            <a><img src="img/banner5.jpg" alt=""></a>
        </div>
        <div class="btns">
            <input type="button" id="left" value="<<<">
            <input type="button" id="right" value=">>>">
</div>

The css is as follows:

.box{width: 1000px;height: 300px;margin: 20px auto;position: relative;overflow: hidden;}
        .box .imgbox{}
        .imgbox a{width: 1000px;height: 300px;position: absolute;left:1000px;top:0;}
        .imgbox a:nth-child(1){left:0;}
        .imgbox img{width: 1000px;height: 300px;}

        .btns input{width: 40px;height: 40px;position: absolute;top:130px;border: none;background: rgba(200,200,200,0.5);}
        #left{left:0;}
        #right{right: 0;}}

js is as follows:

class Banner{
        constructor(){
            this.left = document.getElementById("left");
            this.right = document.getElementById("right");
            this.child = document.querySelectorAll(".imgbox a");

            // Coming in this.iNow = 0;
            //To go this.iPrev = this.child.length - 1;
        }
        init(){
            var that = this;
            this.left.addEventListener("click",function(){
                that.changeIndex(1);
            })
            this.right.addEventListener("click",function(){
                that.changeIndex(2);
            })
        }
        changeIndex(direct){
            if(direct == 1){
                if (this.iNow == 0) {
                    this.iNow = this.child.length-1;
                    this.iPrev = 0;
                }else{
                    this.iNow--;
                    this.iPrev = this.iNow + 1;
                }
            }else{
                if(this.iNow == this.child.length-1){
                    this.iNow = 0;
                    this.iPrev = this.child.length-1;
                }else{
                    this.iNow++;
                    // The index to go to is always the index coming in - 1
                    this.iPrev = this.iNow - 1;
                }
            }
            // Start moving according to the index this.move(direct);
        }
        move(direct){
            if(direct == 1){
                // iPrev goes from 0 to 1000
                this.child[this.iPrev].style.left = 0;
                move(this.child[this.iPrev],{left:1000});
                // iNow comes in// from -1000 to 0
                this.child[this.iNow].style.left = -1000 + "px";
                move(this.child[this.iNow],{left:0});
            }else{
                
                this.child[this.iPrev].style.left = 0;
                move(this.child[this.iPrev],{left:-1000});
                this.child[this.iNow].style.left = 1000 + "px";
                move(this.child[this.iNow],{left:0});
            }
        }
    }

var b = new Banner();
b.init();

The second type: automatic carousel

Introduction: The two left and right buttons can control the left and right switching of the pictures. Click the button with a number below to switch to the number of the picture. During the automatic rotation, the mouse enters to stop the rotation, and the mouse leaves to continue the rotation.

The htm code is as follows:

<div class="box">
        <div class="imgbox">
            <a><img src="../img/banner1.jpg" alt=""></a>
            <a><img src="../img/banner2.jpg" alt=""></a>
            <a><img src="../img/banner3.jpg" alt=""></a>
            <a><img src="../img/banner4.jpg" alt=""></a>
            <a><img src="../img/banner5.jpg" alt=""></a>
        </div>
        <div class="btns">
            <input type="button" id="left" value="<<<">
            <input type="button" id="right" value=">>>">
        </div>
        <div class="list">
        </div>
</div>

The css code is as follows:

.box{width: 1000px;height: 300px;margin: 20px auto;position: relative;overflow: hidden;}
.box .imgbox{}
.imgbox a{width: 1000px;height: 300px;position: absolute;left:1000px;top:0;}
.imgbox a:nth-child(1){left:0;}
.imgbox img{width: 1000px;height: 300px;}

.btns input{width: 40px;height: 40px;position: absolute;top:130px;border: none;background: rgba(200,200,200,0.5);}
        #left{left:0;}
        #right{right: 0;}

.list{width: 1000px;height: 30px;position: absolute;left: 0;bottom: 0;display: flex;background: rgba(200,200,200,0.5);}
.list span{flex: 1;line-height: 30px;text-align: center;border-left:solid 1px black;border-right: solid 1px black;}
.list span.active{background: red;color: #fff;}

The js code is as follows:

class Banner{
        constructor(){
            this.left = document.getElementById("left");
            this.right = document.getElementById("right");
            this.child = document.querySelectorAll(".imgbox a");
            this.list = document.querySelector(".list");
            this.box = document.querySelector(".box");

            this.iNow = 0;
            this.iPrev = this.child.length - 1;
        }
        init(){
            var that = this;
            this.left.addEventListener("click",function(){
                that.changeIndex(1);
            })
            this.right.addEventListener("click",function(){
                that.changeIndex(-1);
            })
            // L3. Event delegation binding event this.list.onclick = function(eve){
                var e = eve || window.event;
                var tar = e.target || e.srcElement;
                if(tar.tagName == "SPAN"){
                    // L4. When the event is triggered, execute the change index and pass the span clicked before the point to that.listChangeIndex(tar);
                }
            }
        }
        changeIndex(direct){
            if(direct == 1){
                if (this.iNow == 0) {
                    this.iNow = this.child.length-1;
                    this.iPrev = 0;
                }else{
                    this.iNow--;
                    this.iPrev = this.iNow + 1;
                }
            }else{
                if(this.iNow == this.child.length-1){
                    this.iNow = 0;
                    this.iPrev = this.child.length-1;
                }else{
                    this.iNow++;
                    this.iPrev = this.iNow - 1;
                }
            }
            this.move(direct);
        }
        move(direct){
            // According to the status of the left and right buttons: left 1, right -1
            //Use multiplication //To change the direction of different buttons this.child[this.iPrev].style.left = 0;
            move(this.child[this.iPrev],{left:this.child[0].offsetWidth * direct});
            this.child[this.iNow].style.left = -this.child[0].offsetWidth * direct + "px";
            move(this.child[this.iNow],{left:0});

            this.setActive();
        }
        createList(){
            // L1. Create spans corresponding to the number of pictures and number them var str = ``;
            for(var i=0;i<this.child.length;i++){
                str += `<span index='${i}'>${i+1}</span>`;
            }
            this.list.innerHTML = str;

            // L2. Set the default current item this.setActive();
        }
        setActive(){
            for(var i=0;i<this.list.children.length;i++){
                this.list.children[i].className = "";
            }
            this.list.children[this.iNow].className = "active";
        }
        listChangeIndex(tar){
            // L5. Determine the index to go out and the index to come in // this.iNow to go out // Get the number of the span clicked to come in var index = parseInt(tar.getAttribute("index"));
            // console.log(this.iNow, index);
            // L6-1. Determine direction if (index > this.iNow) {
                // L7-1. Move left this.listMove(1,index);
            }
            // L6-2. Determine direction if(index < this.iNow){
                // L7-2. Move right this.listMove(-1,index);
            }

            // L8. Set the currently clicked index as the next index to go to this.iNow = index;

            // L9. Set the current item according to the modified index this.setActive();
        }
        listMove(direct,index){
            // this.iNow walks // Where to go, where to go this.child[this.iNow].style.left = 0;
            move(this.child[this.iNow],{left:-1000 * direct})
            // index in// where to come in from and where to go
            this.child[index].style.left = 1000 * direct + "px";
            move(this.child[index],{left:0});
        }
        autoPlay(){
            var t = setInterval(()=>{
                this.changeIndex(-1);
            },2000)

            this.box.onmouseover = function(){
                clearInterval(t);
            }

            var that = this;
            this.box.onmouseout = function(){
                t = setInterval(()=>{
                    that.changeIndex(-1);
                },2000)
            }
            
            // console.log(that);
        }
    }


var b = new Banner();
b.init();
b.createList();
b.autoPlay();

The move in the two cases js is a package of buffered motion, the code is as follows:

function move(ele,obj,cb){
    clearInterval(ele.t);
    ele.t = setInterval(() => {
        // Assume the state is: timer can be cleared var i = true;
        // Because the information in the object is not used until the timer, it is traversed in the timer // and the attributes and target variables obtained in advance for (var attr in obj) {
            if (attr == "opacity") {
                var iNow = getStyle(ele,attr) * 100;
            }else{
                var iNow = parseInt(getStyle(ele,attr));
            }
    
            let speed = (obj[attr] - iNow)/10;
            speed = speed < 0 ? Math.floor(speed) : Math.ceil(speed);
            // As long as one attribute reaches the target, it will stop, which is wrong // All attributes must reach the target before it can stop // As long as one attribute does not reach the target, it must not stop // Use the state to mark whether to stop the timer // As long as one attribute does not reach the target: the timer must not be cleared if (iNow !== obj[attr]) {
                i = false;
            }
            if (attr == "opacity") {
                ele.style.opacity = (iNow + speed)/100;
            }else{
                ele.style[attr] = iNow + speed + "px";
            }
        }
        // If the state is still true after all properties are executed each time the timer is executed, it means that it has not been changed to false. If it has not been changed to false, it means that no property has not reached the end, so the state is still false and will not be cleared if(i){
            clearInterval(ele.t);
            // The user decides the function to be executed when the animation ends. If the user does not pass any parameters, make a default judgment if (cb) {
                cb();
            }
            // cb && cb();
        }
    }, 30);
}

function getStyle(ele,attr){
    if(ele.currentStyle){
        return ele.currentStyle[attr];
    }else{
        return getComputedStyle(ele,false)[attr];
    }
}

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 implement the complete code of the carousel
  • Sample code for implementing carousel with native js
  • js to achieve the effect of supporting mobile phone sliding switch carousel picture example
  • JS carousel diagram implementation simple code
  • js to achieve click left and right buttons to play pictures
  • JS realizes automatic carousel effect (adaptive screen width + mobile phone touch screen sliding)
  • Use html+js+css to achieve page carousel effect (example explanation)
  • JS implements left and right seamless carousel code
  • Native js to achieve infinite loop carousel effect
  • js realizes the sliding carousel effect from left to right

<<:  Detailed tutorial on deploying Springboot or Nginx using Kubernetes

>>:  Detailed explanation of adding security group rules to Alibaba Cloud Server (graphic tutorial)

Recommend

Understand all aspects of HTTP Headers with pictures and text

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

WeChat applet wxs date and time processing implementation example

Table of contents 1. Timestamp to date 2. Convert...

VMware Workstation Pro installs Win10 pure version operating system

This article describes the steps to install the p...

14 techniques for high-performance websites

Original : http://developer.yahoo.com/performance...

Web design and production test questions and reference answers

<br />Web Design and Production Test Part I ...

Detailed explanation of how to use Teleport, a built-in component of Vue3

Table of contents 1. Teleport usage 2. Complete t...

Using CSS3 to implement font color gradient

When using Animation.css, I found that the font o...

How to quickly build a LAMP environment on CentOS platform

This article uses an example to describe how to q...

In-depth explanation of closure in JavaScript

Introduction Closure is a very powerful feature i...

Proxy_pass method in multiple if in nginx location

1. First, let's review the relevant knowledge...

Analysis of MySQL cumulative aggregation principle and usage examples

This article uses examples to illustrate the prin...

About React Native unable to link to the simulator

React Native can develop iOS and Android native a...