随机抽奖

image-20240219125322408

  • 相当于创建9个div,使用绝对定位给他们进行固定
  • 生成一个随机数,选到一个中奖的号码
  • 为了能在转盘上多转几圈,可以扩大随机数的生成范围,到时候直接取模就好了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

<style>
#box {
width: 300px;
height: 300px;
position: relative;
margin: 0 auto;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.4);
}

#box div {
width: 98px;
height: 98px;
line-height: 98px;
border: 1px solid red;
text-align: center;
position: absolute;
}

#box div:nth-child(2) {
left: 100px;
}

#box div:nth-child(3) {
left: 200px;
}

#box div:nth-child(4) {
left: 200px;
top: 100px;
}

#box div:nth-child(5) {
left: 200px;
top: 200px;
}

#box div:nth-child(6) {
left: 100px;
top: 200px;
}

#box div:nth-child(7) {
top: 200px;
}

#box div:nth-child(8) {
top: 100px;
}

#box input {
position: absolute;
width: 98px;
height: 98px;
left: 101px;
top: 101px;
border: 1px solid red;
}

.red {
background-color: red;
}
</style>

</head>

<body>
<div id="box">
<div>一等奖</div>
<div>二等奖</div>
<div>三等奖</div>
<div>四等奖</div>
<div>五等奖</div>
<div>六等奖</div>
<div>七等奖</div>
<div>八等奖</div>
<input type="button" id="startBtn" value="开始">
</div>
<h2></h2>
</body>
<script type="text/javascript">

var box = document.getElementById("box");
var allDiv = document.getElementsByTagName("div");
var startBtn = document.getElementById("startBtn")
var scoreH2 = document.getElementsByTagName("h2")[0];

// console.log(allDiv);

var timer = null;
var flag = false;

startBtn.onclick = function () {

if (flag) {
return;
}

flag = true;

var idx = Math.ceil(Math.random() * 24);
console.log(idx);

var k = 0;

timer = setInterval(function () {
for (var i = 0; i < allDiv.length; i++) {
allDiv[i].className = "";
}
allDiv[k % 8].className = "red";
if (k === idx) {
clearTimeout(timer);
scoreH2.innerText = "恭喜中奖啦!";
flag = false;
}
k++;
}, 100)

}




</script>


</html>