實(shí)現(xiàn)一個(gè)js抽獎(jiǎng)玩玩?
簡(jiǎn)易版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
</head>
<body>
<button>開(kāi)始</button>
<button>停止</button>
<p></p>
</body>
<script>
var btn=document.querySelectorAll("button")[0];
var btn1 = document.querySelectorAll("button")[1];
var p=document.querySelector("p");
var timer=null;
var arrs = ["一等獎(jiǎng)", "二等獎(jiǎng)", "三等獎(jiǎng)", "謝謝", "特等獎(jiǎng)"];
btn.onclick=()=>{ timer = setInterval(() => {
clearInterval(timer);
var arr = arrs[Math.floor(Math.random() * arrs.length)]; p.innerHTML = arr; }, 10); }
btn1.onclick=()=>{ clearInterval(timer) }
</script>
</html>
升級(jí)版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.title {
font-size: 24px;
font-weight: bold;
width: 400px;
height: 70px;
margin: 0 auto;
padding-top: 30px;
text-align: center;
color: #f00;
}
.btns {
width: 190px;
height: 30px;
margin: 0 auto;
}
.btns span {
font-family: '微軟雅黑';
font-size: 14px;
line-height: 27px;
display: block;
float: left;
width: 80px;
height: 27px;
margin-right: 10px;
cursor: pointer;
text-align: center;
color: #fff;
border: 1px solid #eee;
border-radius: 7px;
background: #036;
}
</style>
</head>
<body>
<div id="title" class="title">開(kāi)始抽獎(jiǎng)啦!</div>
<div class="btns">
<span id="play">開(kāi) 始</span>
<span id="stop">停 止</span>
</div>
</body>
<script type="text/javascript">
var data = ['Phone7', 'Ipad', '三星筆記本', '佳能相機(jī)', '惠普打印機(jī)', '謝謝參與', '100元充值卡', '1000元超市購(gòu)物券'],
timer = null, //定時(shí)器
flag = 0; //用于鍵盤(pán)事件狀態(tài)標(biāo)記
window.onload = function() {
var play = document.getElementById('play'),
stop = document.getElementById('stop');
// 開(kāi)始抽獎(jiǎng)
play.onclick = playFun;
stop.onclick = stopFun;
// 鍵盤(pán)事件
document.onkeyup = function(event) {
event = event || window.event;
if (event.keyCode == 13) {
if (flag == 0) {
playFun();
flag = 1;
} else {
stopFun();
flag = 0;
}
}
}
}
// 開(kāi)始抽獎(jiǎng)
function playFun() {
var title = document.getElementById('title');
var play = document.getElementById('play');
//每次都先清除上一次的定時(shí)器任務(wù),避免抽獎(jiǎng)效果累加頻率會(huì)越來(lái)越快
clearInterval(timer);
timer = setInterval(function() {
var random = Math.floor(Math.random() * data.length);
title.innerHTML = data[random];
}, 50);
play.style.background = '#999';
}
//停止抽獎(jiǎng)
function stopFun() {
clearInterval(timer);
var play = document.getElementById('play');
play.style.background = '#036';
}
</script>
</html>
作者:Vam的金豆之路
主要領(lǐng)域:前端開(kāi)發(fā)
我的微信:maomin9761
微信公眾號(hào):前端歷劫之路