实现效果如下:
效果说明:
1、共有90个号码,在点击开始抽奖后,产生随机号码;
2、点击停止后,显示最后一次产生的随机号码,作为幸运号码;
3、在点击三次抽奖后,按钮内容显示为:次数已经用完,再点击时失效;
4、效果图中号码为使用js生成的。
由于涉及的代码量不多,故全部在index.html中,具体代码如下:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>抽奖系统的实现</title>
</head>
<style>
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
#box {
position: relative;
margin: 50px auto;
width: 600px;
height: 540px;
border: 1px solid #f46e00;
}
#show {
float: left;
width: 600px;
height: 460px;
background: #cccccc;
}
#start {
float: left;
width: 100px;
height: 40px;
color: #ededed;
user-select: none;
line-height: 40px;
text-align: center;
margin-left: 250px;
margin-top: 20px;
}
.start {
background: #8a6de9;
}
.list {
float: left;
width: 60px;
height: 51px;
font-size: 24px;
border-radius: 60px;
line-height: 50px;
background: #8a6de9;
text-align: center;
color: #e8e8e8;
}
.stop {
background: #888888;
}
.select {
color: #8a6de9;
background: #e8e8e8;
}
.lucky {
display: none;
position: absolute;
left: 0;
top: 0;
width: 600px;
height: 460px;
line-height: 460px;
text-align: center;
font-size: 56px;
color: #0f0;
background: rgba(0, 0, 0, .7);
}
</style>
<body>
<div id="box">
<div id="show"></div>
<p id="start" class="start">开始抽奖</p>
<div class="lucky"></div>
</div>
<script>
let show = document.getElementById('show');
let start = document.getElementById('start');
let lists = document.getElementsByClassName('list');
let lucky = document.getElementsByClassName('lucky')[0];
let src = '';
let num = 0;
let clickNum = 0;
let interval = 0;
for (let i = 1; i <= 90; i++) {
if (i < 10) {
i = '0' + i;
}
src = src + '<li class="list">' + i + '</li>';
}
show.innerHTML = src;
start.onclick = function () {
if (clickNum < 3) {
if (start.innerText === '停止') {
start.innerText = '再来一次';
clearInterval(interval);
start.setAttribute('class', 'start');
if (num < 10) {
num = '0' + num;
}
lucky.style.display = 'block';
lucky.innerText = "您的中奖号码为:" + num;
} else {
clickNum++;
interval = 0;
clearInterval(interval);
lucky.style.display = 'none';
start.innerText = '停止';
start.setAttribute('class', 'stop');
interval = setInterval(function () {
num = Math.round(Math.random() * 90);
for (let i = 0; i < lists.length; i++) {
lists[i].setAttribute('class', 'list');
if (num - 1 === i) {
lists[i].setAttribute('class', 'select list');
}
}
}, 10)
}
} else {
start.innerText = '次数已用完';
start.style.background = 'rgba(0,0,0,0.7)';
start.style.color = '#fff137';
clearInterval(interval);
lucky.style.display = 'block';
lucky.innerText = "您的中奖号码为:" + num;
}
}
</script>
</body>
</html>
至此,简易的抽奖系统就已经实现完毕。