ES6公用跑马灯抽奖组件的封装及使用
生活随笔
收集整理的這篇文章主要介紹了
ES6公用跑马灯抽奖组件的封装及使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
此組件為本人使用ES6封裝的抽獎組件,以下只分享組件的實現(xiàn)及使用方法,不涉及業(yè)務(wù)相關(guān)代碼。
Lottery.js
解釋請看代碼中的注釋,如果不是太符合需求,可根據(jù)自己的使用場景適當擴展一下…
/*** Created by xieguoqiang on 29/03/2019.*/ export default class Lottery {constructor (giftCount, key) {this.giftCount = giftCount // 禮品個數(shù)this.key = key // 要抽中哪個(內(nèi)幕,你懂的)this.currentIndex = 1 // 當前索引this.currentCycle = 0 // 當前圈數(shù)this.cycles = 6, // 跑的圈數(shù)this.speed = 200 // 速度,即定時器的時間間隔this.classPrefix = 'gift' // 禮品名class前綴this.timer = 0 // 定時器}// 外部調(diào)用方法start () {return new Promise((resolve, reject) => {this.resolve = resolve // 緩存 resolvethis.reject = reject // 緩存 rejectthis.init()})}// 內(nèi)部初始化init () {const before = this.currentIndex === 1 ? this.giftCount : this.currentIndex - 1//設(shè)置上一索引的類名const beforeNode = document.getElementsByClassName(this.classPrefix + before)[0]const beforeClassNewName = beforeNode.className.replace(' active','')beforeNode.className = beforeClassNewName//設(shè)置當前索引的類名const currentNode = document.getElementsByClassName(this.classPrefix + this.currentIndex)[0]currentNode.className += ' active'this.upSpeed()this.downSpeed()this.currentIndex += 1this.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 () {// 增加圈數(shù)if(this.currentIndex === this.giftCount){this.currentCycle += 1}// 如果當前所跑圈數(shù)小于總?cè)?shù)-2 并且 速度小于400,那么減速if(this.currentCycle > this.cycles - 2 && this.speed < 400){this.speed += 20this.stop()this.run()}// 如果當前所跑圈數(shù)大于總?cè)?shù) 且 索引值等于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結(jié)構(gòu)
此組件所實現(xiàn)效果(錄屏來源于互聯(lián)網(wǎng))
總結(jié)
以上是生活随笔為你收集整理的ES6公用跑马灯抽奖组件的封装及使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于mpvue音乐小程序github仓库
- 下一篇: ES6公用花瓣飘落插件的封装及使用,支持