実装アイデア: まず、最も単純な HTML レイアウトはフレックス レイアウトを使用し、ここで書いたように、タイマーを使用して選択項目、1、2、3、4、5、6、7、8、およびサイクル選択を動的に制御します。これは比較的ゴミです。アクティブなアイテムが加算され続けると判断され、8 に達すると 1 にリセットされます。一貫した効果であるように見えます。その後、最初に速度が低下する効果があります。定義は判断しましたが、タイマーの時間を5で割る、つまりコードが実行されるたびに一定の量が減算され、タイマーの実行時間はこの時間を 5 で割った値よりも大きい場合、現在の時間が追加されます。つまり、タイマーの実行が遅くなります。コードをアップロードして確認するだけです。
<template>
<div class="luckDraw-container">
<div v-for="item in dataList" :key="item.key" class="luckDraw-item" :class="{ active: activeIndex === item.key }" @click="() => start(item)">
<div>
{
{ item.content ? item.content : '开始' }}
{
{ item.key }}
</div>
</div>
<div> 中奖号码:{
{ winActive }} </div>
</div>
</template>
<script lang="ts" setup name="luckDraw">
import { onMounted, reactive, ref } from 'vue';
const props = defineProps({
// 速度
speed: {
type: Number,
default: 200
}
});
// 随机选中一个开始进行抽奖
const activeIndex = ref(null);
const dataList = reactive([
{
key: 1,
content: '谢谢惠顾'
},
{
key: 2,
content: '一等奖'
},
{
key: 3,
content: '谢谢惠顾'
},
{
key: 8,
content: '谢谢惠顾'
},
{
key: 0
},
{
key: 4,
content: '三等奖'
},
{
key: 7,
content: '谢谢惠顾'
},
{
key: 6,
content: '二等奖'
},
{
key: 5,
content: '谢谢惠顾'
}
]);
// 中奖号码
const winActive = ref(null);
// 定时器
const timer = ref(null);
// 速度
const speed = ref(props.speed);
// 点击开始
function start(item: { key: number; content: string }) {
if (timer.value || item.key != 0) return;
if (!activeIndex.value) {
activeIndex.value = parseInt(Math.random() * 8 + 1);
}
winActive.value = parseInt(Math.random() * 8 + 1);
luckDraw();
}
const lock = ref(false);
// 抽奖成功
function luckDraw() {
if (speed.value > 0) {
// 控制九宫格选中的速度,当速度是当前的五分之一的时候,就让速度变慢
const half = parseInt(props.speed / 5);
if (lock.value) {
speed.value += 5;
if (speed.value >= props.speed) {
// 中奖一共八个宫格,如果中奖在其他的宫格,就多加几个 步速,一直到中奖
if (winActive.value === activeIndex.value) {
clearInterval(timer.value);
speed.value = props.speed;
timer.value = null;
lock.value = false;
return;
}
}
// 速度再加快
} else if (!lock.value) {
speed.value -= 5;
if (half >= speed.value) {
lock.value = true;
}
}
// 选中样式
if (activeIndex.value == 8) activeIndex.value = 1;
else activeIndex.value++;
// 执行抽奖方法
timer.value = setTimeout(luckDraw, speed.value);
}
}
onMounted(() => {});
</script>
<style lang="scss" scoped>
.luckDraw-container {
width: 500px;
height: 500px;
border-radius: 10px;
border: 1px solid #000;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
user-select: none;
.luckDraw-item {
width: 150px;
height: 150px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10px;
cursor: pointer;
}
.active {
background-color: #ffa500;
}
}
</style>