這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)可鍵盤控制的抽獎(jiǎng)系統(tǒng)的相關(guān)資料,需要的朋友可以參考下
JS原理:建立一個(gè)數(shù)組用來(lái)存儲(chǔ)抽獎(jiǎng)內(nèi)容,例如 iphone6 等,當(dāng)點(diǎn)擊開(kāi)始的時(shí)候,開(kāi)啟定時(shí)器,產(chǎn)生一個(gè)隨機(jī)數(shù),把對(duì)應(yīng)文本的innerHTML改成數(shù)組所對(duì)應(yīng)的內(nèi)容。
如果想讓某個(gè)抽獎(jiǎng)幾率變高,可以讓數(shù)組中某個(gè)值重復(fù)次數(shù)多點(diǎn)。接下來(lái)看代碼。、
JavaScript代碼
window.onload = function(){
var data = [
"iphone 6s plus",
"蘋果Mac 筆記本",
"美的洗衣機(jī)",
"凌美鋼筆",
"謝謝參與",
"索尼入耳式耳機(jī)",
"雷柏機(jī)械鍵盤",
"《javaScript高級(jí)程序設(shè)計(jì)》",
"精美保溫杯",
"維尼小熊一只",
"500元中國(guó)石化加油卡",
"愛(ài)奇藝年費(fèi)會(huì)員",
"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>抽獎(jiǎng)啦</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="index.js"></script>
</head>
<body>
<div id="container">
<h1 id="text">iphone 6s plus</h1>
<p>小提示:您可以按下Enter鍵來(lái)控制開(kāi)始暫停,祝您中大獎(jiǎng)喲</p>
<div id="btns">
<span id="btn-start">開(kāi)始</span>
<span id="btn-stop">停止</span>
</div>
</div>
</body>
</html>
希望本文所述對(duì)大家的學(xué)習(xí)有所幫助,輕松實(shí)現(xiàn)抽獎(jiǎng)系統(tǒng)。