最近過活動要做個老虎機(jī)效果,發(fā)現(xiàn)網(wǎng)上找的幾乎都是以前的jq寫的,找了一個后看了看代碼,感覺寫了的比較麻煩,然后自己寫了一個簡單的。主要是用css3來實現(xiàn)轉(zhuǎn)動加速減速的效果。應(yīng)為需要獲取設(shè)置元素高度等問題,為了方便引入了jq,如果不依賴jq可吧用jq的地方改成原生js。
<template>
<div>
<div class="box">
<div class="groups animation-ease" v-for="k in 3" @webkitTransitionEnd="endGame(k)">
<ul class="group-item" v-for="i in (round+1)" >
<li class="prize-item" v-for="item in prizes">{{item}}</li>
</ul>
</div>
</div>
<div @click="startClick">{{disClick?'抽獎中...':'點(diǎn)擊開始'}}</div>
</div>
</template>
<script>
import $ from 'jquery'
export default {
data(){
return {
round:6,//轉(zhuǎn)幾回合后停下來
prizes:[1,2,3,4,5,6,7,8,9,11,12,13,14,15],
disClick:false,//防止多次點(diǎn)擊
itemHeight:0,//每個獎品的高度
prize_id:'',//中獎id
}
},
mounted(){
this.itemHeight = $('.prize-item').outerHeight()
$('.groups').css('height',this.itemHeight * this.prizes.length*(this.round+1))
},
methods:{
startClick(){//開始抽獎
if(this.disClick){
return
}
//獲取中獎的id
let index = parseInt(Math.random()*this.prizes.length);
this.prizd_id = this.prizes[index];
this.runGame(index)
},
runGame(index){//啟動抽獎
this.disClick = true;
this.resetGame();
var itemHeight = this.itemHeight;
var groupsHeight = this.round*$('.group-item').height();
$('.groups').each(function(e){
var pos = index*itemHeight + groupsHeight
setTimeout(()=>{
$(this).addClass('animation-ease').css('transform','translate3d(0, -'+pos+'px, 0)')
},e*300)
})
},
endGame(k){//抽獎結(jié)束后的回調(diào)
if(k==3){
alert('恭喜您中了'+this.prizd_id)
this.disClick = false;
}
},
resetGame(){//重置狀態(tài)
$('.groups').removeClass('animation-ease').css('transform','');
}
}
}
</script>
<style lang="less" scoped>
.box{
width:300px;
height:100px;
overflow: hidden;
background: #fff;
.animation-ease{
transition-property:transform;
transition-duration: 3s;
transition-timing-function: ease;
}
.groups{
float: left;
width:100px;
text-align: center;
.prize-item{
width:100px;
height:100px;
font-size:50px;
}
}
}
</style>