JS-抽獎系統-實現原理

來源:互聯網
上載者:User

標籤:

有本事中獎的,過來找我換紅包!!哈哈!!

 

<meta charset="UTF-8">

<title>抽獎系統</title>
<style type="text/css">

.wrap {width: 300px;margin: 20px auto;text-align: center;}.box {padding: 10px;color: red;font: bold 24px "微軟雅黑";border: 1px solid #FF7F50;color: red;margin: 20px auto;}input[type="button"] {border: 1px solid #DC143C;background-color: #FF6600;padding: 5px 12px;font: bold 16px "微軟雅黑";color: white;cursor: pointer;}.box,input[type="button"] {-webkit-border-radius: 11px;-moz-border-radius: 11px;border-radius: 11px;}input[type="button"].play {background-color: brown;border: 1px solid darkred;}
style

</style>

<div class="wrap"><div id="box" class="box">開始抽獎了!</div><input type="button" value="開始" id="play" /><input type="button" value="結束" id="stop" /></div>
html

<script type="text/javascript">
window.onload = function() {
var title = document.getElementById(‘box‘),
play = document.getElementById(‘play‘),
stop = document.getElementById(‘stop‘),
arr = [‘謝謝參與!‘, ‘一等獎‘, ‘謝謝參與!‘, ‘二等獎‘, ‘謝謝參與!‘, ‘三等獎‘, ‘特等獎‘, ‘謝謝參與!‘, ‘優秀獎‘, ‘參與獎‘, ‘謝謝參與!‘, ‘榮譽獎‘, ‘謝謝參與!‘, ‘辛苦獎‘, ‘謝謝參與!‘, ‘魅力獎‘, ‘謝謝參與!‘], //思路出錯的地方2,抽獎就是抽隨機數,而不是一個i從0-7的加加加,最後只會是7的結果。
trap = 0, //方便二次按斷行符號時結束抽獎【一鍵多用!】
timer = null; //思路出錯的地方1,定時器要定義為全域變數

//開始抽獎
play.onclick = playCj; //因為需要多次引用,所以封裝起來函數。
//結束抽獎
stop.onclick = stopCj;

//封裝開始抽獎函數
function playCj() {
clearInterval(timer);
//設定定時器
timer = setInterval(function() {
var i = Math.floor(Math.random() * arr.length);
//random產生的是0-1之間的隨機數,拿這個例子舉例來說,他需要產生的是0-7範圍的隨機數才能正確取出arr數組內的文字。因為數組長度是8,而產生的是0-1之間的小數點,再乘以8的話,最大也就是7.999999999,然後利用Math.floor()向下取整,去掉小數點之後的數,就可以得到自己的索引目標。
title.innerHTML = arr[i];
}, 30);
play.className = ‘play‘; //更改樣式直接用了一個class名字,這樣js裡省點代碼。
}
//封裝結束函數
function stopCj() {
play.className = ‘‘;
clearInterval(timer);
title.innerHTML = ‘謝謝參與!‘;
}
//鍵盤事件
document.onkeyup = function(event) { //忘記先傳一個event事件,因為沒有一個具體的接受鍵盤事件的對象,所以用document
event = event || window.event;
//console.log(event.keyCode);
if(event.keyCode===13){//這裡兩個等號或三個等號都可以
alert(trap)
if(trap==0){//這裡判斷要用兩個等號,用三個等號就是錯誤的了。因為是判斷是不是等於,而一個等號是賦值!!!注意了
playCj();
trap=1;
}else{
stopCj();
trap=0;
}
}
}
}
http://www.imooc.com/video/2292

 

JS-抽獎系統-實現原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.