原生JS实现九宫格抽奖
程序员文章站
2022-03-10 14:41:44
本文实例为大家分享了js实现九宫格抽奖的具体代码,供大家参考,具体内容如下上代码:
谢谢惠顾
...本文实例为大家分享了js实现九宫格抽奖的具体代码,供大家参考,具体内容如下
上代码:
<div class="wrapper"> <div>谢谢惠顾</div> <div>十万元现金</div> <div>谢谢惠顾</div> <div>iphone11</div> <div>抽奖</div> <div>美的冰箱</div> <div>谢谢惠顾</div> <div>50元红包</div> <div>谢谢惠顾</div> </div> <div class="result"></div>
css样式代码:
<style> .wrapper { width: 300px; height: 300px; display: flex; flex-flow: row wrap; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; border: 1px solid red; } .wrapper div { flex: none; width: 100px; height: 100px; box-sizing: border-box; border: 1px solid red; display: flex; align-items: center; justify-content: center; } .active { background-color: red; } .wrapper div:nth-child(5) { cursor: pointer; } .result { height: 100px; display: inline-block; position: absolute; top: 50px; left: 0; right: 0; margin: auto; text-align: center; line-height: 100px; font-size: 40px; font-weight: 700; color: #ff4400; } </style>
js代码:
<script> var t, m, num, time, index, target, current; //以索引值为0,1,2,5,8,7,6,3的div元素为循环目标, //因为以num总数递减的方式进行循环,故将数组倒序定义 var arr = [3, 6, 7, 8, 5, 2, 1, 0]; var div = document.queryselectorall('.wrapper div'); var result = document.queryselector('.result'); div[4].onclick = function() { clearinterval(time); div[4].innerhtml = '抽奖中...'; result.innerhtml = ''; //中奖目标设为0到7的随机整数 target = math.floor(math.random() * 8); //起始位置设为随机,且以num为总的循环数 num = math.floor(math.random() * 8) + 40; //将总循环数的2/3保存,方便调整速率峰值出现的时间 //若m为总循环的1/2,则速度峰值会在总时长的中间出现 m = math.floor(num * 2 / 3); //此处if语句可限制中奖,从第一个开始外圈顺时针分别对应7,6,5,4,3,2,1,0 //如设置target == 6 即限制中十万元现金,以下代码为100%不中奖 if (target == 6|| target == 4 || target == 2 || target == 0) { target++; } speed(); function speed() { //将循环目标div的索引值转换为循环总数的表达式 index = arr[num % 8]; //给当前循环元素添加样式,并移除之前的样式 if (current) { current.remove('active'); } div[index].classlist.add('active'); current = div[index].classlist; //速度函数,可调试速率 t = math.floor(math.pow((num - m), 2) + 250); //一次性定时器,嵌套递归循环控制速度 time = settimeout(function() { speed() }, t) //判断中奖结果 if (num == target) { cleartimeout(time); div[4].innerhtml = '抽奖'; switch (target) { case 6: result.innerhtml = '恭喜您抽中' + div[arr[target % 8]].innerhtml + '大奖'; break; case 4: result.innerhtml = '恭喜您抽中' + div[arr[target % 8]].innerhtml; break; case 2: result.innerhtml = '恭喜您抽中' + div[arr[target % 8]].innerhtml; break; case 0: result.innerhtml = '恭喜您抽中' + div[arr[target % 8]].innerhtml; break; default: result.innerhtml = div[arr[target % 8]].innerhtml; } } num--; } } </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。