Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2019-11-30 17:05:33
forward
3247 people have browsed it

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!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template