您的位置:首页 > Web前端 > JQuery

案例九 、jQuery游戏,来抽个奖吧

2017-04-01 21:58 267 查看
今天要写的是,利用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.c
4000
om/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
);
},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>


这个案例比较简单,所以就不赘述了,下面附上最后的效果图:

这个是点击了开始按钮之后,人员名进行快速的切换中:



下面这个是点击了停止按钮的最终中奖人员和对应的奖品



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery 游戏 抽奖游戏