-
我们所需要实现的就是:点击抽奖→高亮滚动(匀速的或非匀速的)→停止在某个图标上,在这我使用到的框架是vue2,实现的关键在于动态class!
-
这个是画的简易的画面,主要是实现的思想~
-
所有的代码如下:
<div class="box">
<div
class="list"
v-for="(item,index) in 9"
:key="index"
:class="{checked:checkedIndex===index}"
>
{{index}}
<button v-if="index===4" class="start" @click="running()">开始抽奖</button>
</div>
</div>
</template>
<script>
export default {
name: "APP",
data() {
return {
checkedIndex: "",
currentIndex: "",
timerId: null,
list: [0, 1, 2, 5, 8, 7, 6, 3],
targetIndex: "",
circle: 0
};
},
methods: {
running() {
this.currentIndex = 0;
this.circle++;
clearInterval(this.timerId);
this.timerId = setInterval(() => {
if (this.targetIndex === this.currentIndex && this.circle === 5) {
clearInterval(this.timerId);
this.circle = 0;
console.log("恭喜您中将啦 -----> ");
}
this.checkedIndex = this.list[this.currentIndex];
this.currentIndex++;
if (this.currentIndex >= 8) {
this.running();
}
}, 100 + this.circle * 50);
}
},
created() {
this.targetIndex = Math.floor(Math.random() * 8);
console.log(this.targetIndex);
}
};
</script>
<style scoped>
.box {
width: 610px;
border: 1px solid #000;
margin: 20px auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.list {
width: 200px;
height: 200px;
background-color: red;
border: 1px solid #000;
margin-bottom: 1px;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
position: relative;
}
.checked {
color: red;
font-size: 60px;
background-color: yellow;
}
.start {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
font-size: 40px;
font-weight: 700;
}
.start:hover {
cursor: pointer;
background-color: burlywood;
}
</style>
-
接下来听我吹:样式啥的没啥好说的就是遍历生成一堆盒子然后搞一个相对绝对定位把抽奖按钮定位到上边就行啦,至于盒子里边的文字是偷懒直接渲染下标了,①点击按钮→触发方法running→延时器每过100毫秒执行一次→checkedIndex=this.list[this.currentIndex]→ ②:class="{checked:checkedIndex===index}",通过以步骤就能动态的将选中class按照顺时针依次添加给到每个盒子→ ③ if (this.currentIndex >= 9) { this.running(); }当转完一圈的时候,那就重新转一圈→④if (this.currentIndex === this.targetIndex && this.circle === 5) { clearInterval(this.timerId); this.circle = 0; console.log("恭喜您中将啦 -----> "); }如果转够了5圈(circle===5,因为每次running, this.circle++;)就在this.currentIndex === this.targetIndex的位置停止
-
1、Q为啥定义list?A 为了能让样式的切换能够按照顺时针(也就是看到的盒子的下标)转动;
-
效果