uniapp九宫格抽奖

最近写uniapp的九宫格跑马灯抽奖!!! 一开始没什么思路,,看了之后的大佬文章原来很简单!!!

核心思路:就是 动态的 i++ 改变下标再加上动态类名,以及定时器

直接看效果图上代码~!!1

 

 1、先定义html 

<div class="rotary_table">
    <div v-for="(item, index) of awards" :key="index">
      <div
        class="award"
        :class="['award' + index, { active: index == current }]"
      >
        {{ item.name }}
      </div>
      <van-button
        id="start-btn"
        :disable="disable"
        type="primary"
        @click="start()“
      ></van-button>
      <!-- <el-button disable id="start-btn" @click="start()"></el-button> -->
    </div>
  </div>

2、样式这里使用的是绝对定位

.rotary_table {
  width: 621px;
  height: 621px;
  position: relative;
  margin: 20px auto;
}
.award {
  width: 179px;
  height: 179px;
  text-align: center;
  float: left;
  position: absolute;
  overflow: hidden;
  background: pink;
}
.active {
  background-color: #fffea5 !important;
}

.ward0 {
  top: 21px;
  left: 21px;
}
.award1 {
  top: 21px;
  left: 221px;
}
.award2 {
  top: 21px;
  right: 21px;
}
.award3 {
  top: 221px;
  right: 22px;
}
.award4 {
  bottom: 22.5px;
  right: 22px;
}
.award5 {
  bottom: 22.5px;
  right: 221px;
}
.award6 {
  bottom: 22.5px;
  left: 21px;
}
.award7 {
  top: 221px;
  left: 21px;
}
#start-btn {
  position: absolute;
  width: 179px;
  height: 179px;
  top: 221px;
  left: 221px;
  border-radius: 50%;
  text-align: center;
  background: url('../assets/cj_xz.png') no-repeat center/100%;
}
3、赋给他们初始值
   awards: [
        { id: 1, name: 10 },
        { id: 2, name: 100 },
        { id: 3, name: 2 },
        { id: 4, name: 1 },
        { id: 5, name: 5 },
        { id: 6, name: '石头今天学习了吗' },
        { id: 7, name: 0 },
        { id: 8, name: 5 }
      ],
   timer: null, 
      time: 0, // 当前的时间戳
      award: {}, // 后端返回来的抽中的奖品
      speed: 200,
      diff: 15,
      current: 0, // 当前的索引值
      noClick: true   这儿是加了一个过度点击 还是存在一点问题

4、函数

methods: {
  // 点击抽奖
 start() {
      this.getLottery()
      this.time = Date.now()
    },
 // 调接口获取奖品
    getLottery() {
      this.award.name = '恭喜石头学了25个小时'
      this.award.id = 6
      this.move()
    },
// 转盘事件
  move() {
      this.timer = setTimeout(() => {
        this.current++
        if (this.current > 7) {
          this.current = 0
        }
        // 若抽中的奖品id存在,则开始减速转动
        if (this.award.id && (Date.now() - this.time) / 1000 > 2) {
          this.speed += this.diff
          // 若转动时间超过4秒,并且奖品id等于小格子的奖品id,则停下来
          if (
            (Date.now() - this.time) / 1000 > 4 &&
            this.award.id == this.awards[this.current].id
          ) {
            clearTimeout(this.timer)
            setTimeout(() => {
              alert(`恭喜${this.award.name}`)
            }, 0)
            return
          } else {
            // 若抽中的奖品不存在,则加速转动
            this.speed -= this.diff
          }
        }
        this.move()
      }, this.speed)
    }
}
 
 
小白第一篇博客 欢迎大佬指正!! 觉得写得好给个点赞,谢谢~~·

posted on 2022-09-09 10:26  张德俊~  阅读(889)  评论(0编辑  收藏  举报

导航