Home Web Front-end JS Tutorial How to achieve dynamic carousel effect with JavaScript? (code example)

How to achieve dynamic carousel effect with JavaScript? (code example)

Nov 30, 2019 pm 05:05 PM
javascript carousel

The content of this article is how to achieve dynamic carousel effect using JavaScript? (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to achieve dynamic carousel effect with JavaScript? (code example)

Function description:

1. Move the mouse left and right The side arrow is displayed, and the arrow is hidden when the mouse leaves.

2. Dynamically add a small circle at the bottom and bind the click event, and synchronize the click event of the small circle with the click event of the left and right arrows

3. Copy the first picture and add it to ul. Finally, you can add pictures dynamically

4. Bind the click event to the arrow and make the picture Can rotate seamlessly

5. Implement automatic rotation (animation function)

Specific implementation code:

1. The left and right arrows are displayed when the mouse moves in, and the arrows are hidden when the mouse leaves.

con.addEventListener('mouseenter', function() {
    arrow_l.style.display = 'block';  // 将左右箭头的display设为block
    arrow_r.style.display = 'block';
});
con.addEventListener('mouseleave', function() {
    arrow_l.style.display = 'none';  // 将左右箭头display设为none
    arrow_r.style.display = 'none';
});
Copy after login

2. Dynamically add a small circle at the bottom and bind the click event , and synchronize the click event of the small circle with the click event of the left and right arrows

 for(var i = 0; i < ul.children.length; i++) {
    var li = document.createElement(&#39;li&#39;);
    li.setAttribute(&#39;index&#39;, i);  // 通过添加自定义属性来记录小圆圈索引号
    ol.appendChild(li);      // 将创建的li添加进ol里
    // 生成小圆圈的同时就可以给它绑定单击事件
    li.addEventListener(&#39;click&#39;, function() {
        // 排他思想 干掉所有人,留下我自己
        for(var i = 0; i < ol.children.length; i++) {  // 先把所有的小圆圈改为未选中状态
            ol.children[i].className = &#39;&#39;;
        }
        // 再把当前小圆圈改为选中状态
        this.className = &#39;current&#39;;
        var index = this.getAttribute(&#39;index&#39;);  // 获取当前小圆圈的索引
        // 将index值赋值给num以及circle,将小圆圈的点击事件和左右箭头点击事件同步
        num = index;
        circle = index;
        animate(ul, - index * conWidth);
    })
}
Copy after login

3. Copy the first picture and add it to ul. Finally, you can dynamically add pictures

// 克隆第一张图片
var first = ul.children[0].cloneNode(true); // true 深拷贝
ul.appendChild(first); // 拷贝第一张图片添加到ul最后
Copy after login

4. Bind a click event to the arrow and enable the picture to rotate seamlessly

①Click event of the arrow on the right

var num = 0;    // 用来存储点击后图片序号
var circle = 0;   // 用来存储点击后小圆圈序号
var flag = true;   // flag 节流阀 防止用户点击过快 图片播放太快
// 右侧箭头点击播放
arrow_r.addEventListener(&#39;click&#39;, function() {
    if(flag) {
        // 点击后先关闭节流阀
        flag = false;
        // 如果播放到了最后一张,就把left直接值设为0从头播放,同时还原num
        if(num == ul.children.length - 1) {
            ul.style.left = 0;
            num = 0;
        }
        num++;
        animate(ul, - num * conWidth, function() {
            // 回调函数 动画执行完后开启节流阀
            flag = true;
        });
        // 小圆圈和箭头一起变化
        circle++;
        /* if(circle == ol.children.length) {
              circle = 0;
           } */
        // 可以用三元运算符判断小圆圈是否到了最后一个,如果是最后一个就还原circle
        circle == ol.children.length ? circle = 0 : circle;
        circleChange();   // 使当前小圆圈为选中状态(重复代码封装到一个函数里了)
    }
})
Copy after login

②Click event of the left arrow

arrow_l.addEventListener(&#39;click&#39;, function() {
    if(flag) {
        // 首先关闭节流阀
        flag = false;
        // 如果播放到了第一张,就把left值设为最后一张的值
        if(num == 0) {
            num = ul.children.length - 1;
            ul.style.left = - num * conWidth + &#39;px&#39;;
        }
        num--;
        animate(ul, - num * conWidth, function() {
            flag = true;
        });
        // 小圆圈和箭头一起变化 
        circle--;
        // 三元表达式   circle < 0 时说明是第一张图片,将小圆圈改为第四个(索引为3)
        circle < 0 ? circle = ol.children.length - 1 : circle;
        circleChange();
    }
})
Copy after login

circleChange();Function code

// 小圆圈的选中状态(相同代码可以封装为一个函数,使代码更简洁)
function circleChange() {
    // 排他思想
    for(var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = &#39;&#39;;
    }
    ol.children[circle].className = &#39;current&#39;;
}
Copy after login

5. Implementation Automatic carousel (animation function)

// 自动播放轮播图,相当于隔一段时间调用一次右侧箭头点击事件
 var timer = setInterval(function() {
     // 手动调用点击事件
     arrow_r.click();
}, 2000);
Copy after login

Animation function animate.js (ps: I did not write this into index.js below, this You have to get it in yourself, you can introduce it as an animate.js file or paste it directly into your js code)

// obj 动画对象
// target 目标位置
// callback 回调函数
function animate(obj, target, callback) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function() {
        var step = (target - obj.offsetLeft) / 10;  // step步长值
        step = step > 0 ? Math.ceil(step) : Math.floor(step); // 大于零向上取整,小于零向下取整
        if(obj.offsetLeft == target) {
            clearInterval(obj.timer);
            // if(callback) { // 判断是否传了回调函数
            //     callback(); // 回调函数,当动画执行完后才执行
            // }
            // &&是短路运算符,存在callback时才会继续执行callback()
            callback && callback();
        }
        obj.style.left = obj.offsetLeft + step + 'px';
    }, 15)
}
Copy after login

The specific implementation code is as follows:

HTML code:

<div class="con">
    <i class="icon iconfont iconarrow_left arrow-l"></i>
    <i class="icon iconfont iconarrow_right arrow-r"></i>
    <ul>
        <li>
            <a href="javascript:;"><img src="images/img1.jpg" alt=""></a>
        </li>
        <li>
            <a href="javascript:;"><img src="images/img2.jpg" alt=""></a>
        </li>
        <li>
            <a href="javascript:;"><img src="images/img3.jpg" alt=""></a>
        </li>
        <li>
            <a href="javascript:;"><img src="images/img4.jpg" alt=""></a>
        </li>
        <li>
            <a href="javascript:;"><img src="images/img5.jpg" alt=""></a>
        </li>
    </ul>
    <ol>
    </ol>
</div>
Copy after login

ps: The small arrows on my left and right sides are Iconfont icons (iconarrow_left, iconarrow_right), to be introduced

<link rel="stylesheet" href="http://at.alicdn.com/t/font_1518420_oljcm07nn2.css">
Copy after login

CSS code:

<style>
    * {
        margin: 0;
        padding: 0;
    }
    ul,li,ol,a {
        list-style: none;
        text-decoration: none;
    }
    .con {
        width: 533px;
        height: 300px;
        margin: 100px auto;
        position: relative;
        background-color: #f0f0f0;
        overflow: hidden;
    }
    .arrow-l,.arrow-r{
        display: none;
        width: 20px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #eee;
        position: absolute;
        top: 45%;
        background-color: rgba(0, 0, 0, 0.2);
        z-index: 2;
        cursor: pointer;
    }
    .arrow-l {
        left: 0;
    }
    .arrow-r{
        right: 0;
    }
    ul {
        position: absolute;
        width: 600%;
    }
    ul li {
        float: left;
    }
    ul li img {
        width: 533px;
        height: 300px;
    }
    ol {
        position: absolute;
        left: 50%;
        bottom: 8px;
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
    }
    ol li {
        float: left;
        width: 6px;
        height: 6px;
        margin: 0 2px;
        border-radius: 50%;
        border: 2px solid rgba(255, 255, 255, 0.5);
        cursor: pointer;
    }
    .current {
        background-color: #ffe;
    }
</style>
Copy after login

Detailed JavaScript code (index.js)

 window.addEventListener('load', function() {   // 等页面加载完毕
    // 获取需要用到的的元素
    var arrow_l = document.querySelector('.arrow-l');
    var arrow_r = document.querySelector('.arrow-r');
    var con = document.querySelector('.con');
    var conWidth = con.offsetWidth;
    // 鼠标经过箭头显示,鼠标离开箭头隐藏
    con.addEventListener('mouseenter', function() {
        arrow_l.style.display = 'block';  // 将左右箭头的display设为block
        arrow_r.style.display = 'block';
        // 鼠标经过停止定时器
        clearInterval(timer);
        timer = null; // 释放定时器变量
    });
    con.addEventListener('mouseleave', function() {
        arrow_l.style.display = 'none';  // 将左右箭头display设为none
        arrow_r.style.display = 'none';
        // 鼠标离开再重新开启定时器
        timer = setInterval(function() {
            // 手动调用点击事件
            arrow_r.click();  // 自动轮播
        }, 2000);
    });
    
    var ul = con.querySelector('ul');
    var ol = con.querySelector('ol');
    // 动态添加底部小圆圈
    for(var i = 0; i < ul.children.length; i++) {
        var li = document.createElement('li');
        // 通过添加自定义属性来记录小圆圈索引号
        li.setAttribute('index', i);
        ol.appendChild(li);
        // 生成小圆圈的同时就可以给它绑定单击事件
        li.addEventListener('click', function() {
            // 排他思想 干掉所有人,留下我自己
            for(var i = 0; i < ol.children.length; i++) {  // 先把所有的小圆圈改为未选中状态
                ol.children[i].className = '';
            }
            // 再把当前小圆圈改为选中状态
            this.className = 'current';
            var index = this.getAttribute('index');  // 获取当前小圆圈的索引
            // 将index值赋值给num以及circle,将小圆圈的点击事件和左右箭头点击事件同步
            num = index;
            circle = index;
            animate(ul, - index * conWidth);
        })
    }
    // 让第一个小圆圈底色为白色(选中状态)
    ol.children[0].className = 'current';
    // 克隆第一张图片
    var first = ul.children[0].cloneNode(true);  // true 深拷贝
    ul.appendChild(first); // 拷贝第一张图片添加到ul最后

    var num = 0;    // 用来存储点击后图片序号
    var circle = 0;   // 用来存储点击后小圆圈序号
    var flag = true;   // flag 节流阀 防止用户点击过快 图片播放太快
    // 右侧箭头点击播放
    arrow_r.addEventListener('click', function() {
        if(flag) {
            // 点击后先关闭节流阀
            flag = false;
            // 如果播放到了最后一张,就把left直接值设为0从头播放,同时还原num
            if(num == ul.children.length - 1) {
                ul.style.left = 0;
                num = 0;
            }
            num++;
            animate(ul, - num * conWidth, function() {
                // 回调函数 动画执行完后开启节流阀
                flag = true;
            });
            // 小圆圈和箭头一起变化
            circle++;
            /* if(circle == ol.children.length) {
                  circle = 0;
               } */
            // 可以用三元运算符判断小圆圈是否到了最后一个,如果是最后一个就还原circle
            circle == ol.children.length ? circle = 0 : circle;
            circleChange();   // 使当前小圆圈为选中状态
        }
    })

    // 左侧箭头点击播放
    arrow_l.addEventListener('click', function() {
        if(flag) {
            // 关闭节流阀
            flag = false;
            // 如果播放到了第一张,就把left值设为最后一张的值
            if(num == 0) {
                num = ul.children.length - 1;
                ul.style.left = - num * conWidth + 'px';
            }
            num--;
            animate(ul, - num * conWidth, function() {
                flag = true;
            });
            // 小圆圈和箭头一起变化 
            circle--;
            // circle < 0 时说明是第一张图片,将小圆圈改为第四个(索引为3)
            if(circle < 0) {
                circle = ol.children.length - 1;
            }
            circleChange();
        }
    })
    // 小圆圈的选中状态(相同代码可以封装为一个函数,使代码更简洁)
    function circleChange() {
        // 排他思想
        for(var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        ol.children[circle].className = 'current';
    }
    // 自动播放轮播图,相当于隔一段时间调用一次右侧箭头点击事件
    var timer = setInterval(function() {
        // 手动调用点击事件
        arrow_r.click();
    }, 2000);
})
Copy after login

More cool CSS3, html5, javascript special effects codes, all in: javascript special effects collection

The above is the detailed content of How to achieve dynamic carousel effect with JavaScript? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles