每天一个JS 小demo之“随机”抽奖。主要知识点:Math函数,数组方法,递归

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.list {
margin: 50px auto;
padding: 0;
list-style-type: none;
width: 300px;
position: relative;
}
.list li {
position: absolute;
border: 1px solid #000;
width: 98px;
height: 98px;
text-align: center;
line-height: 98px;
font-size: 20px;
}
.list li:nth-of-type(1){
left: 0;
top: 0;
}
.list li:nth-of-type(2){
left: 100px;
top: 0;
}
.list li:nth-of-type(3){
left: 200px;
top: 0;
}
.list li:nth-of-type(4){
left: 200px;
top: 100px;
}
.list li:nth-of-type(5){
left: 100px;
top: 100px;
}
.list li:nth-of-type(6){
left: 200px;
top: 200px;
}
.list li:nth-of-type(7){
left: 100px;
top: 200px;
}
.list li:nth-of-type(8){
left: 0px;
top: 200px;
}
.list li:nth-of-type(9){
left: 0px;
top: 100px;
}
.list span {
display: block;
height: 100%;
background: #ccc;
}
.list .show {
background: #f60;
color: #fff;
}
</style>
<script type="text/javascript">
window.onload = function(){
var spans = document.querySelectorAll('span');
var a = document.querySelector('a');
var nub = 5;
var timer = 0;
a.onclick = function(){
var target = [0,1,5,2,7];
var length = (Math.round(Math.random()*4) + 2)*spans.length+1+target[Math.floor(Math.random()*target.length)];
var arr = [];
var now = 0;
var delay = 50;
console.log(length);
for(var i = 0; i < length; i++){
arr.push(i);
}
setShow();
function setShow(){
timer = setTimeout(function(){
for(var i = 0; i < spans.length; i++){
spans[i].className = "";
}
spans[arr[now]%spans.length].className = "show";
now++;
//递归终止条件
if(now < arr.length){
delay += 10;
setShow();
}
},delay);
}
};
};
</script>
</head>
<body>
<ul class="list">
<li>
<span>三等奖</span>
</li>
<li>
<span>谢谢惠顾</span>
</li>
<li>
<span>三等奖</span>
</li>
<li>
<span>二等奖</span>
</li>
<li>
<a href="#">开始抽奖</a>
</li>
<li>
<span>一等奖</span>
</li>
<li>
<span>谢谢惠顾</span>
</li>
<li>
<span>二等奖</span>
</li>
<li>
<span>三等奖</span>
</li>
</ul>
</body>
</html>

上一篇:cocos2d(背景图片循环滚动)


下一篇:JQ方法实用案例///鼠标移动到div和修改ipt中弹窗、CSS鼠标变小手、JQ获取元素属性、JQ选择器