ES6公用跑馬燈抽獎組件的封裝及使用

前言

此組件爲本人使用ES6封裝的抽獎組件,以下只分享組件的實現及使用方法,不涉及業務相關代碼。

Lottery.js

解釋請看代碼中的註釋,如果不是太符合需求,可根據自己的使用場景適當擴展一下…

/**
 * Created by xieguoqiang on 29/03/2019.
 */
export default class Lottery {
    constructor (giftCount, key) {
        this.giftCount = giftCount   // 禮品個數
        this.key = key               // 要抽中哪個(內幕,你懂的)
        this.currentIndex = 1        // 當前索引
        this.currentCycle = 0        // 當前圈數
        this.cycles = 6,             // 跑的圈數
        this.speed =  200            // 速度,即定時器的時間間隔
        this.classPrefix = 'gift'    // 禮品名class前綴
        this.timer = 0               // 定時器
    }
    // 外部調用方法
    start () {
        return new Promise((resolve, reject) => {
            this.resolve = resolve // 緩存 resolve
            this.reject = reject   // 緩存 reject
            this.init()
        })
    }
    // 內部初始化
    init () {
        
        const before = this.currentIndex === 1 ? this.giftCount : this.currentIndex - 1
        
        //設置上一索引的類名
        const beforeNode = document.getElementsByClassName(this.classPrefix + before)[0]
        const beforeClassNewName = beforeNode.className.replace(' active','')
        beforeNode.className = beforeClassNewName
        //設置當前索引的類名
        const currentNode = document.getElementsByClassName(this.classPrefix + this.currentIndex)[0]
        currentNode.className += ' active'
        
        this.upSpeed()
        this.downSpeed()
        
        this.currentIndex += 1
        this.currentIndex = this.currentIndex > this.giftCount ? 1 : this.currentIndex        
    }
    // 加速
    upSpeed () {
        if (this.currentCycle < 2 && this.speed > 100){
            this.speed -= 5 * this.currentIndex 
            this.stop()
            this.run()
        }
    }
    // 減速
    downSpeed () {
        // 增加圈數
        if(this.currentIndex === this.giftCount){
            this.currentCycle += 1
        }
        // 如果當前所跑圈數小於總圈數-2 並且 速度小於400,那麼減速
        if(this.currentCycle > this.cycles - 2 && this.speed < 400){
            this.speed += 20
            this.stop()
            this.run()
        }
        
        // 如果當前所跑圈數大於總圈數 且 索引值等於key,那麼停止奔跑
        if(this.currentCycle > this.cycles && this.currentIndex === this.key){
            this.stop()
            this.resolveResult()
        }
    }
    // 停止
    stop() {
        clearInterval(this.timer)
    }
    // 跑動
    run () {
        this.timer = setInterval(() => {
            this.init()
        }, this.speed)
    }
    // 返回中獎索引
    resolveResult () {
        this.resolve(this.key)
    }
}

使用方法

①:import Lottery from ‘./Lottery’
在這裏插入圖片描述

dom結構

在這裏插入圖片描述

此組件所實現效果(錄屏來源於互聯網)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章