本文小编为大家详细介绍“原生JavaScript怎么实现九宫格抽奖”,内容详细,步骤清晰,细节处理妥当,希望这篇“原生JavaScript怎么实现九宫格抽奖”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
思路:通过移动背景颜色实现中奖信息,每一个方形元素,需要按顺序排列,加个延时器,当到最后一个的时候让它从0开始就可以动起来了,!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 600px;
height: 600px;
margin: 0 auto;
position: relative;
}
#box div {
width: 198px;
height: 198px;
border-radius: 10px;
/* border: 1px solid red; */
text-align: center;
line-height: 198px;
background-color: #ffe8e8;
position: absolute;
}
.btns {
text-align: center;
}
.active {
background-color: rgb(255, 94, 0) !important;
}
#start,#end{
width: 100px;
height: 30px;
background-color: rgb(24, 105, 255);
color: white;
}
</style>
</head>
<body>
<div id="box"></div>
<br>
<div class="btns">
<button id="start">开始</button>
<button id="end">停止</button>
</div>
<script>
var box = document.getElementById('box');
var start = document.getElementById('start');
var end = document.getElementById('end');
// 所有奖品
var allList = ['宇宙战将', '白起', '太阳系级宇宙战舰', '小破木船', '地球级宇宙战将', '月球级蘸酱', '太阳级蘸酱', '大西洋级蘸酱'];
// 允许抽中的奖品
var list = ['太阳系级宇宙战舰','白起']; // 想要中的奖品放进去
for (let i = 0; i < allList.length; i++) {
box.innerHTML += `<div>${allList[i]}</div>`;
}
box.children[1].style.left = '200px';
box.children[2].style.left = '400px';
box.children[3].style.left = '400px';
box.children[3].style.top = '200px';
box.children[4].style.left = '400px';
box.children[4].style.top = '400px';
box.children[5].style.top = '400px';
box.children[5].style.left = '200px';
box.children[6].style.top = '400px';
box.children[7].style.top = '200px';
var running = false;
var flag = true;
var active = 0;
var time = 200;
var goods = '';
box.children[active].className = 'active';
start.onclick = function () {
if (!running) { // 只有当没有在抽奖中的时候,才让点击开始
running = true; // 重置
time = 200; // 重置
f1();
}
}
end.onclick = function () {
if (running) { // 只有当正在抽奖中的时候才让点击停止
flag = false;
goods = list[Math.floor(Math.random() * list.length)]; // 0, 1, 2随机的一个值
}
}
// 如果使用定时器,time会锁死不会改变;通过延时器模拟定时器的方法,是可以改变定时的时间
function f1() {
box.children[active].className = '';
active++;
if (active > 7){ // 因为是从0开始计算所以写7
active = 0;
}
box.children[active].className = 'active';
if (flag) { // 抽奖速度越来越快
time -= 10;
if (time < 50) {
time = 50;
}
} else { // 抽奖速度越来越慢
time += 10;
if (time > 300) {
time = 300;
// 判断当前滚动到的奖品是否是内定的奖品
if (box.children[active].textContent === goods ) {
flag = true;
running = false;
setTimeout(() => {
alert(goods); // 弹出抽奖信息
}, 500);
return; // 抽中奖品后,停止抽奖
}
}
}
setTimeout(f1,time);
}
</script>
</body>
</html>
读到这里,这篇“原生JavaScript怎么实现九宫格抽奖”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。