JS实现抽奖器
- setInterval()函数设置计数器,第一个参数放函数,第二个放毫秒值 为 让其结束让setInterval()函数返回一个标志timer, 然后 clearInterval(timer)
- 注意:getElementsByClassName()返回的是数组,要加序号。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.wapper{
border:2px solid red;
text-align: center;
margin: 0 auto;
width: 50%;
border-radius: 10px;
height: 300px;
}
.top{
line-height: 35px;
color: red;
background: #FFC0CB 5px 5px;
}
button{
border-radius: 8px;
background: #01a1ff;
margin-top: 10px;
color: white;
padding: 10px 15px;
}
button:hover{
border-radius: 8px;
background: black;
margin-top: 10px;
color: white;
padding: 10px 15px;
}
</style>
<body>
<div class="wapper">
<div class="top">开始抽奖了!</div>
<button class="butt-start">开始</button>
<button class="butt-stop">停止</button>
</div>
<script> //7个谢谢参与,2个鼠标,1个耳机
var gifts=[
"蓝牙耳机",
"谢谢参与",
"谢谢参与",
"无线鼠标",
"谢谢参与",
"谢谢参与",
"无线鼠标",
"谢谢参与",
"谢谢参与",
"谢谢参与",
];
var gift=document.getElementsByClassName("top")[0];
var start=document.getElementsByClassName("butt-start")[0];
var stop=document.getElementsByClassName("butt-stop")[0];
var timer=null;
//设置计时器,没10毫秒换一次
start.onclick=function(){
timer=setInterval( function () {
gift.innerHTML=gifts[Math.floor(Math.random()*gifts.length)]
},10)
};
//停止,清除计时器
stop.onclick=function(){
clearInterval(timer);
}
</script>
</body>
</html>
