今天要寫的是,利用jQuery寫一個抽獎的案例,頁面包含四個組件,兩個按鈕分別是開始和停止的按鈕。兩個box,分別盛放人員和獎品。當點擊開始按鈕時,人員不停地進行切換。抽獎的box中顯示等待抽獎結果。當按下停止按鈕時,兩個盒子分別顯示人員名,和所中的獎品。
頁面的效果圖如下:

可能頁面沒有那么好看。我們主要實現的是功能
首先在body中定義組件
<body><input type = "button" class = "btn" id = "start" value = "開始"><input type = "button" class = "btn" id = "stop" value = "停止"><div id = "number" class = "box1"></div><div id = "jiangpin" class = "box2"></div></body>
再進行樣式設置:
css代碼:
<style type="text/css"> *{ margin: 0px; padding: 0px; } .btn{ width: 90px; height: 40px; background-color: lightgreen; color: white; font-size: 18px; font-family: "微軟雅黑"; text-align: center; line-height: 40px; } .box1{ position: absolute; width: 230px; height: 100px; margin: 10px 50px; top:150px; left: 60%; background-color: gold; color: black; border-radius: 8%; font-size: 30px; text-align: center; line-height: 100px; } .box2{ position: absolute; width: 230px; height: 100px; margin: 10px 50px; top: 300px; left: 60%; background-color: gold; color: black; border-radius: 8%; font-size: 30px; text-align: center; line-height: 100px; } </style>接下來就是寫函數了。在這里我引用的是”http://libs.baidu.com/jquery/1.9.0/jquery.js“;的jQuery庫。
<script >$(document).ready(function(){// 1. 首先第一步定義兩個數組,存放人員和獎品var list1 = [ 'A君' , ' B君 ' , ' C君 ' , ' D君 ', ' E君 ' , ' F君 ' , ' G君 '];var list2 = ['YSL', ' iphone7', ' iphone6', ' 手表', ' 小紅花', ' 謝謝參與',' 謝謝參與',' 謝謝參與'];// 2. 為開始按鈕綁定點擊事件$("#start").click(function(){ //2.1 先將獎品的盒子中的內容初始化 $("#jiangpin").html("等待抽獎中..."); //2.2 利用setInterval()函數進行人員名字切換 // 定義一個變量去接受它每次的狀態 functionId = setInterval(function(){ var n = Math.floor(Math.random() * list1.length); $("#number").html(list1[n]); },30); });// 3. 為停止按鈕綁定點擊事件 $("#stop").click(function(){ // 3.1 清除setInterval()。并停止在最后一次的人員名上 clearInterval(functionId); // 3.2 隨機產生獎品數組的下標,并將下標對應的元素寫入獎品區 var jiang = Math.floor(Math.random() * list2.length); $("#jiangpin").html(list2[jiang]); });})</script>這個案例比較簡單,所以就不贅述了,下面附上最后的效果圖:
這個是點擊了開始按鈕之后,人員名進行快速的切換中:

下面這個是點擊了停止按鈕的最終中獎人員和對應的獎品


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答