js制作九宫格抽奖功能

HTML代码:

<div id="lottery">
  <div class="lottery-item">1</div>
  <div class="lottery-item">2</div>
  <div class="lottery-item">3</div>
  <div class="lottery-item">4</div>
  <div class="lottery-item">5</div>
  <div class="lottery-item">6</div>
  <div class="lottery-item">7</div>
  <div class="lottery-item">8</div>
  <div class="lottery-item">9</div>
</div>
<button id="start-btn">开始抽奖</button>

CSS代码:

#lottery {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: #e6e6e6;
}
.lottery-item {
  width: 100px;
  height: 100px;
  font-size: 50px;
  text-align: center;
  line-height: 100px;
  background-color: #fff;
  border: 1px solid #ccc;
}
.lottery-active {
  background-color: orange;
}

JavaScript代码:

var items = document.getElementsByClassName('lottery-item');
var btn = document.getElementById('start-btn');
var index = 0;
var timer = null;

btn.onclick = function() {
  if(timer) {
    clearInterval(timer);
    timer = null;
    // 停止时将当前选中项背景色还原
    items[index].classList.remove('lottery-active');
  } else {
    timer = setInterval(function() {
      // 先将当前选中项背景色还原
      items[index].classList.remove('lottery-active');
      index ++;
      if(index > 8) {
        index = 0;
      }
      // 设置当前选中项的背景色
      items[index].classList.add('lottery-active');
    }, 100);
  }
}

通过点击按钮,可以开始或停止抽奖的功能。其中,抽奖的动画效果是通过定时器实现的,每隔一段时间改变当前选中项的背景色来模拟抽奖的过程。当停止抽奖时,定时器会被清除,当前选中项的背景色会还原。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值