制作一个简易的抽奖系统!欢迎大家学习!
JS原理:建立一个数组用来存储抽奖内容,例如 iphone6 等,当点击开始的时候,开启定时器,产生一个随机数,把对应文本的innerHTML改成数组所对应的内容。
如果想让某个抽奖几率变高,可以让数组中某个值重复次数多点。接下来看代码。、
JavaScript代码
window.onload = function(){ var data = [ "iphone 6s plus", "苹果Mac 笔记本", "美的洗衣机", "凌美钢笔", "谢谢参与", "索尼入耳式耳机", "雷柏机械键盘", "《javaScript高级程序设计》", "精美保温杯", "维尼小熊一只", "500元中国石化加油卡", "爱奇艺年费会员", "iPad mini", "32G U盘", ]; var bStop = true; var timer = null; var btns = document.getElementById('btns').getElementsByTagName('span'); var text = document.getElementById('text'); btns[0].onclick = start; btns[1].onclick = stop; document.onkeyup = function(event){ event = event||window.event; if(event.keyCode==13){ if(bStop){ start(); }else { stop(); } } } function start(){ clearInterval(timer); timer = setInterval(function(){ var r = Math.floor(Math.random()*data.length); text.innerHTML = data[r]; },20); btns[0].style.background = '#666'; bStop = false; } function stop(){ clearInterval(timer); btns[0].style.background = 'blue'; bStop = true; } }
html css 代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>抽奖啦</title> <style> * { margin: 0; padding:0; } #container { width: 500px; height: 200px; margin: 100px auto; background: red; position: relative; padding-top: 20px; } #container p { position: absolute; bottom: 4px; left: 30px; } #btns { position: absolute; left: 118px; bottom: 30px; } #container h1 { color: #fff; text-align: center; } #btn-start,#btn-stop { width: 100px; height: 60px; background: blue; text-align: center; line-height: 60px; font-size: 20px; display: inline-block; color: #fff; margin-right: 60px; border-radius: 10px; cursor: pointer; } </style> <script src="https://www.jb51.net/index.js"></script> </head> <body> <div> <h1>iphone 6s plus</h1> <p>小提示:您可以按下Enter键来控制开始暂停,祝您中大奖哟</p> <div> <span>开始</span> <span>停止</span> </div> </div> </body> </html>