search
HomeWeb Front-endJS TutorialHow to achieve carousel effect in js

How to achieve carousel effect in js

Apr 12, 2018 pm 04:03 PM
javascriptCarousel

The content of this article is to share with you how to achieve the carousel effect in js. It has a certain reference value. Friends in need can refer to it.

There are many examples on the Internet , the seamless scrolling I do here is to make the picture appear left and right scrolling by changing the left value of the element.
Let’s first take a look at the structural style of p css:
How to achieve carousel effect in js
p css code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{         
                   margin: 0;                
                   padding: 0;            
              }
            ul,ol{       
                   list-style: none;            
              }
            /*消除图片底部3像素距离*/
            img{         
                   vertical-align: top;           
                }
            .scroll{         
                   width: 500px;               
                   height: 200px;               
                   margin: 100px auto;                
                   border: 1px solid #ccc;                
                   padding: 7px;                
                   overflow: hidden;                
                   position: relative;            
             }
            .box{         
                   width: 500px;                
                   height: 200px;                
                   overflow: hidden;                
                   position: relative;            
             }
            .box ul{          
                  width: 600%;                
                  position: absolute;                
                  left: 0;                
                  top: 0;            
             }
            .box ul li{         
                   float: left;            
            }
            .scroll ol{       
                     position: absolute;                
                     right: 10px;                
                     bottom: 10px;            
            }
            .scroll ol li{         
                   float: left;                
                   width: 20px;                
                   height: 20px;                
                   background: pink;                
                   text-align: center;                
                   line-height: 20px;                
                   border-radius: 50%;                
                   background-color: pink;             
                margin-left:10px ;                
                cursor: pointer;            }
            .scroll ol li.current{        
                    background-color: purple;            }
        </style>
    </head>
    <body>
        <p id="scroll" class="scroll">
            <p id="box" class="box">
                <ul id="ul">
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/1.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/2.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/3.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/4.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/5.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                </ul>
                <ol id="ol">
                    <li class="current">1</li>
                    <li>2</li>
                    <li>3</li>
                    <li>4</li>
                    <li>5</li>
                </ol>
            </p>
        </p>
    </body></html>

The display effect is as shown in the figure:
How to achieve carousel effect in js
Next we want to js code,
Before we do this, we must understand that the small dots 1 2 3 are not hard-coded. It is determined based on the number of pictures in ul li, so we must first put p in ol li Remove the code
To achieve seamless scrolling, you need one more picture, that is, clone the first picture and put it at the end. At this time, the css layout is retained, and only p is left:

<body>
        <p id="scroll" class="scroll">
            <p id="box" class="box">
                <ul id="ul">
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/1.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/2.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/3.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/4.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                    <li><img  src="/static/imghwm/default1.png"  data-src="images/5.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to achieve carousel effect in js" ></li>
                </ul>               
            </p>
        </p>
    </body>

At this time, we use js code to generate small dots

var scroll = document.getElementById("scroll"); // 获得大盒子
        var ul = document.getElementById("ul"); // 获得ul
        var ulLis = ul.children;// 获得ul的盒子 以此来生成ol中li的个数
        var liWidth = ul.children[0].offsetWidth;// 获得每个li的宽度
        // 操作元素
        // 因为要做无缝滚动,所以要克隆第一张,放到最后一张后面
        // 1. 克隆元素
        ul.appendChild(ul.children[0].cloneNode(true));        // 2.创建ol 和li
        vaar ol = document.createElement("ol");//创建ol元素
        scroll.appendChild(ol);// 把ol放到scroll盒子里面去
        for (var i=0;i<ulLis.length-1;i++) {            var li = document.createElement("li");// 创建li元素
            li.innerHTML = i + 1;// 给li里面添加文字  1 2 3 4 5
            ol.appendChild(li);// 将li元素添加到ol里面
        }
        ol.children[0].className = "current";// ol中的第一个li背景色为purple

At this time, after the ol li element, which is the small dot, is created, we continue to use js for animation
The animation part includes:
1. When the mouse passes through several small dots, which picture will be displayed, and the color of the small dots also changes
2. Automatic carousel of pictures , (this requires a timer)
3. When the mouse passes over the picture, the picture stops playing automatically (this requires clearing the timer)
4. When the mouse leaves the picture, the picture continues to rotate automatically (restart the timer)
Here we encapsulate an animate() animation function

// 动画函数 第一个参数,代表谁动  第二个参数 动多少
        // 让图片做匀速运动,匀速动画的原理是 当前的位置 + 速度  即 offsetLeft + speed

        function animate(obj,target){
            // 首先清除掉定时器
            clearInterval(obj.timer);            // 用来判断 是+ 还是 -  即说明向左走还是向右走
            var speed = obj.offsetLeft < target ? 15 : -15;
            obj.timer = setInterval(function(){
                var result = target - obj.offsetLeft;//它们的差值不会超过speed
                obj.style.left = obj.offsetLeft + speed + "px";                // 有可能有小数的存在,所以在这里要做个判断             
                if (Math.abs(result) <= Math.abs(speed)) {
                    clearInterval(obj.timer);
                    obj.style.left = target + "px";
                }
            },10);
        }

Timer function

var timer = null; // 轮播图的定时器
        var key = 0;// 控制播放的张数
        var circle = 0;// 控制小圆点

        timer = setInterval(autoplay,1000);// 自动轮播
        function autoplay(){
            /*自动轮播时,要对播放的张数key进行一个判断,如果播放的张数超过ulLis.length-1,
            就要重头开始播放.  因为我们克隆了第一张并将其放在最后面,所以我们要从第二张图片开始播放*/
            key++; // 先++
            if(key > ulLis.length-1){// 后判断

                ul.style.left = 0; // 迅速调回
                key = 1; // 因为第6张是第一张,所以播放的时候是从第2张开始播放
            }            // 动画部分
            animate(ul,-key*liWidth);            // 小圆点circle   当显示第几张图片是,对应的小圆点的颜色也发生变化 

            /*同理,对小圆点也要有一个判断*/
            circle++;            if (circle > olLis.length-1) {
                circle = 0;
            }            // 小圆点颜色发生变化
            for (var i = 0 ; i < olLis.length;i++) {                // 先清除掉所用的小圆点类名
                olLis[i].className = ""; 
            }            // 给当前的小圆点 添加一个类名
            olLis[circle].className = "current";

        }

Okay, here we show the main code, the specific code, check here to download js to achieve the carousel effect

The above is the detailed content of How to achieve carousel effect in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor