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