Home > Web Front-end > JS Tutorial > Implementation method of carousel chart on mobile terminal (source code attached)

Implementation method of carousel chart on mobile terminal (source code attached)

不言
Release: 2018-10-15 14:00:06
forward
3937 people have browsed it

The content of this article is about the implementation method of carousel chart on mobile terminal (source code attached). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article introduces the principle of seamless carousel chart implementation on the mobile terminal. This wheel is relatively simple, but it can be a convenient reference for students who are just getting started. The final effect is seamless and infinite sliding on the mobile terminal, and the speed of the carousel can be customized. Supports left and right sliding gestures. The source code will be posted at the end.

HTML part

   <div class="outer" id="oneTest">
        <div class="inner">
            <div class="goIndex item" goUrl="https://www.baidu.com"
                 style="background-image:url(1.jpg)"></div>
            <div class="goIndex item" goUrl="https://www.baidu.com"
                 style="background-image:url(2.jpg)"></div>
            <div class="goIndex item" goUrl="https://www.baidu.com"
                 style="background-image:url(3.jpg)"></div>
        </div>
        <ul class="num"></ul>
    </div>
Copy after login

The html of the carousel image is like this. We will look at it with the css, and then we will go to the css.

Css part

 * {
        margin: 0;
        padding: 0;
    }
    ul {
        list-style: none;
    }
    .outer {
        margin: 0 auto;
        width: 100%;
        height: 150px;
        overflow: hidden;
        position: relative;
    }
    .inner {
        height: 150px;
        overflow: hidden;
        width: 8000px;
    }
    .inner .goIndex {
        float: left;
        height: 150px;
        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;
    }
    .num {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 20%;
        display: flex;
        justify-content: center;
        flex-direction: row;
        align-items: center;
    }
    .num li {
        margin: 0 3px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: rgba(0, 0, 0, .2);
    }
    .num li.select {
        background: rgba(0, 0, 0, .7);
    }
Copy after login

We can see through css that .outer is the outermost shell, and the excess parts will be hidden. .inner is a very long container, and item For a single item. The structure is relatively simple. ul is a small control point, but the mobile terminal does not have the function of clicking on small points.

The Js part of the page

    //function dGun(obj = {})   这是dGun.js的主函数
    // 初始化两个图片轮播
    dGun({id:"oneTest",time:10000});
    dGun({id:"twoTest",time:4000});
    // 点击后跳转
    var goList = document.getElementsByClassName("goIndex");
    for (var i = 0; i < goList.length; i++) {
        goList[i].addEventListener("click", function () {
            window.location = this.getAttribute("goUrl")
        })
    }
Copy after login

dGun() is to initialize the carousel image. We need to pass in parameters. The first parameter id is the id of the .outer box, and the second parameter is the automatic switching time. . Below is a simple click to jump function.

dGun.js initialization part

     //function dGun(obj = {}) 包裹全部dGun内代码
    var id = obj.id;                                           //获取domid
    var time = obj.time ? parseInt(obj.time) : 3000;           //默认3s
    time = time > 300 ? time : 1000;                           //间隔必须大于300
    var _width = document.querySelector("#"+id).offsetWidth;   //获取轮播图宽度
    var _index = 0;                                             //当前是第几个轮播 从-1开始
    var inner = document.querySelector("#"+id+" .inner");               //获取轮播内容外壳(很长的那个)
    var items = document.querySelectorAll("#"+id+" .item");             //获取轮播元素

    // 将第一个元素复制到最后,将最后的元素复制到开头
    var firstItem = items[0];
    var lastItem = items[items.length-1];
    inner.insertBefore(lastItem.cloneNode(true),firstItem);
    inner.appendChild(firstItem.cloneNode(true));
    inner.style.transform = "translateX(-"+_width+"px)";
    // 生成底部小圆点
    var imgLength = document.querySelector("#"+id+" .inner").children.length-2;
    var makeCir = '<li class="select"></li>';
    for (var i = 0; i < imgLength - 1; i++) {
        makeCir += &#39;<li></li>';
    }
    document.querySelector("#"+id+" .num" ).innerHTML = makeCir;
    //设置轮播的宽度。
    var newItems = document.querySelectorAll("#"+id+" .item");
    for(var i = 0; i<newItems.length;i++){
        newItems[i].style.width = _width+"px";
    }
Copy after login

I won’t introduce the first few lines of code, which is to get the dom and get the width.
Here we talk about copying the first element to the end and copying the last element to the beginning. This is the key to achieving seamlessness. For example, we have 3 pictures 1/2/3 for rotation, so we need Change the dom node to 3/1/2/3/1. Why do you do this? The principle of the carousel chart is that multiple items are juxtaposed. We change the value through translateX to display different areas. We first change the dom node to 3/ 1/2/3/1, and then use inner.style.transform = "translateX(-" _width "px)"; this code will place the initialization carousel display area on the picture 1. Then people slide to the right. When sliding to 3, sliding right again should display 1, and the right side of 3 in our dom node is 1. In this way, when sliding right to 1 at the end, we quickly move to the position of 1 at the beginning through translateX To achieve seamless carousel.

Gesture sliding implementation

    var startX = 0, changedX = 0, originX = 0, basKey = 0;
    //手指点击的X位置    滑动改变X的位置    inner的translateX的值    basKey是个钥匙

    function Broadcast() {
        var that = this;
        this.box = document.querySelector("#"+id+" .inner");
        this.box.addEventListener("touchstart", function (ev) {
            that.fnStart(ev);
        })
    }

    // 轮播手指按下
    Broadcast.prototype.fnStart = function (ev) {
        clearInterval(autoPlay);          //手指按下的时候清除定时轮播
        if (!basKey) {
            var that = this;
            startX = ev.targetTouches[0].clientX;
            var tempArr = window.getComputedStyle(inner).transform.split(",");
            //获取当前偏移量
            if (tempArr.length > 2) {
                originX = parseInt(tempArr[tempArr.length - 2]) || 0;
            }
            this.box.ontouchmove = function (ev) {
                that.fnMove(ev)
            }
            this.box.ontouchend = function (ev) {
                that.fnEnd(ev)
            }
        }
    };
    // 轮播手指移动
    Broadcast.prototype.fnMove = function (ev) {
        ev.preventDefault();
        changedX = ev.touches[0].clientX - startX;
        var changNum = (originX + changedX);
        this.box.style.cssText = "transform: translateX(" + changNum + "px);";
    };
    // 轮播手指抬起
    Broadcast.prototype.fnEnd = function (ev) {
        // 移除底部按钮样式
        document.querySelector("#"+id+" .select").classList.remove("select");
        basKey = 1;
        setTimeout(function () {
            basKey = 0;
        }, 300)
        if (changedX >= 100) {                   //向某一方向滑动
            var _end = (originX + _width);
            this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
            _index--;
            if (_index == -1) {                //滑动到第一个了,为了实现无缝隙,滚到最后去
                document.querySelectorAll("#"+id+" .num>li")[imgLength - 1].classList.add("select");
                play(-1);
            }
        } else if (changedX < -100) {         //向负的某一方向滑动
            var _end = (originX - _width);
            this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
            _index++;
            if (_index == imgLength) {       //滑到最后一个了,为了实现无缝隙,滚到前面去
                play(imgLength);
                document.querySelectorAll("#"+id+" .num>li")[0].classList.add("select");
            }
        } else {                          //滑动距离太短,没吃饭不用管
            this.box.style.cssText = "transform: translateX(" + originX + "px);transition:all .3s";
        }
        // 完成一次滑动初始化值
        startX = 0;
        changedX = 0;
        originX = 0;
        if (_index != -1 && _index != imgLength) {
            document.querySelectorAll("#"+id+" .num>li")[_index].classList.add("select");
        }
        this.box.ontouchmove = null;            //清除事件
        this.box.ontouchend = null;             //清除绑定事件
        autoPlay = setInterval(lunbo, time)      //开启轮播
    }
Copy after login

We define the Broadcast method to monitor the user's touch screen press event
When the finger presses, we record the X-axis position of the finger pressed. Listen for move and lift events.
What we have to do when the finger moves is to calculate the offset and change the position of the inner through the offset.
When the finger is lifted, we check that the offset is greater than 100. This value can be changed, or it can be changed to pass a parameter. Determine the direction by positive and negative, and determine the current number by index. If it slides to the first and last node we copied, the play function will be executed, which we will explain next. Then it is relatively simple to change the control point style, and finally initialize the value and clear the listening event.

play function, quick scroll

    //首尾无缝连接
    function play(index) {
        setTimeout(function () {
            inner.style.transition = 'all 0s';
            if (index == -1) {
                var _number = -imgLength * _width;
                inner.style.transform = 'translateX(' + _number + 'px)';
                _index = imgLength - 1;
            } else if (index == imgLength) {
                inner.style.transform = 'translateX(-' + _width + 'px)';
                _index = 0;
            }
        }, 250);
    }
Copy after login

The principle is to quickly set the sliding change time to 0 when the picture sliding is completed, and change translateX to the position where it should go.

Timing switching pictures

    function lunbo(){
        document.querySelector("#"+id+" .select").classList.remove("select");
        var tempArr = window.getComputedStyle(inner).transform.split(",");
        if (tempArr.length > 2) {
            originX = parseInt(tempArr[tempArr.length - 2]) || 0;
        }
        var _end = (originX - _width);
        inner.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
        _index++;
        if (_index != -1 && _index != imgLength) {
            document.querySelectorAll("#"+id+" .num>li")[_index].classList.add("select");
        }else if(_index == -1 ){
            document.querySelectorAll("#"+id+" .num>li")[imgLength - 1].classList.add("select");
        } else if (_index == imgLength) {
            play(imgLength);
            document.querySelectorAll("#"+id+" .num>li")[0].classList.add("select");
        }
    }
    // 初始化轮播
    var autoPlay = setInterval(lunbo,time);       //开启轮播
    var _Broadcast = new Broadcast();             //实例触摸
Copy after login

This is to start a timer, offset the inner X by a fixed time, and determine whether to execute the play function based on the number.

https://github.com/Zhoujiando... The source code is here, you can take a look.

The above is the detailed content of Implementation method of carousel chart on mobile terminal (source code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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