ES6公用跑马灯抽奖组件的封装及使用
生活随笔
收集整理的這篇文章主要介紹了
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 // 緩存 resolvethis.reject = reject // 緩存 rejectthis.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 += 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 () {// 增加圈數if(this.currentIndex === this.giftCount){this.currentCycle += 1}// 如果當前所跑圈數小于總圈數-2 并且 速度小于400,那么減速if(this.currentCycle > this.cycles - 2 && this.speed < 400){this.speed += 20this.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結構
此組件所實現效果(錄屏來源于互聯網)
總結
以上是生活随笔為你收集整理的ES6公用跑马灯抽奖组件的封装及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于mpvue音乐小程序github仓库
- 下一篇: 重返帝国能赚钱吗