1. 程式人生 > >原生js實現淘寶輪播圖,支援左右和跳轉(滑鼠點多快都不會亂)。

原生js實現淘寶輪播圖,支援左右和跳轉(滑鼠點多快都不會亂)。

用transform是因為這個比left的效能好。

這個是演示網址(不要直接存下來哦):https://shalltears.github.io/test-sowing-map/ 。

這個是完整程式碼下載地址,覺得還行的下載支援一下:https://download.csdn.net/download/zmdmwh/10802716 。

下面還是直接上js程式碼吧。

var obj = {
    sleepTime: 2000,//輪播延時
    cont: 1,//第幾張
    step: -500,//步距
    state: true,//左為false,右為true
    origin: document.getElementsByClassName('main-img')[0],//拿到全部圖片的父級
    btn: document.getElementsByClassName('btn'),//左右按鈕
    mainLi: document.getElementsByTagName('li'),//圓圈
    init: function () {//主函式
        this.bottomStateChange(this.cont);
        this.timer();
        this.click();
    },
    move: function (origin) {//移動
        this.state == true ? this.cont++ : this.cont--;
        clearInterval(timer1);
        origin.style.transform = 'translate3d(' + this.cont * this.step + 'px,0px,0px)';
        origin.style.transitionDuration = '0.3s';
        this.sleepTime = 2000;
        this.timer();
        this.cont > 4 && this.state == true ? this.change(origin, 0) : 0;
        this.cont < 0 && this.state == false ? this.change(origin, 4) : 0;
        this.bottomStateChange(this.cont);
    },
    change: function (origin, cont) {//特殊處理
        clearInterval(timer1);
        this.cont = cont;
        origin.style.transitionDuration = '0s';
        origin.style.transform = 'translate3d(' + this.cont * this.step + 'px,0px,0px)';
        this.sleepTime = 50;
        this.timer();
    },
    timer: function () {//計時器
        timer1 = setInterval(function () {
            obj.move(obj.origin);
            obj.state = true;
        }, obj.sleepTime)
    },
    click: function () {//幾個點選事件
        obj.btn[0].onclick = function () {
            obj.state = false;
            obj.move(obj.origin);
        }
        obj.btn[1].onclick = function () {
            obj.state = true;
            obj.move(obj.origin);
        }
        for (var i = 0; i < 4; i++) {
            (function (i) {
                obj.mainLi[i].onclick = function () {
                    obj.state = true;
                    obj.cont = i;
                    obj.move(obj.origin);
                }
            }(i));
        }
    },
    bottomStateChange: function (cont) {//下面的點點
        for (var i = 0; i < 4; i++) {
            obj.mainLi[i].className = 'main-li';
        }
        cont > 0 ? obj.mainLi[cont - 1].className = 'main-li-2' : obj.mainLi[3].className = 'main-li-2';
    }
}
obj.init();

其實還有一個小bug待處理,就是有時候(機率不太大)點完向左後,下一次定時跳轉會先向左一下才能正常接著走,應該是重置obj.state的位置不太好,有好辦法的朋友可以幫幫忙~