下面是一个简单的随机抽取的小案例
点击开始按钮,停止后随机获取一个数字
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box{
border: 1px solid #CCCCCC;
width: 300px;
height: 300px;
background-color: lavenderblush;
text-align: center;
line-height: 300px;
font-size: 50px;
}
</style>
</head>
<body>
<div id="box"></div>
<input type="button" value="开始" id="btn">
<input type="button" value="停止" id="stop">
<script>
var arr=[1,2,3,4,5,6,7,8];
var btn = document.getElementById("btn"),
stop= document.getElementById("stop"),
box = document.getElementById("box"),
index = 0,
time = null;
btn.onclick = function(){
time=setInterval(function(){
box.innerHTML = arr[index];
index++;
if(index>arr.length-1){
index = 0;
}
},100);
}
stop.onclick = function(){
clearInterval(time);
}
</script>
</body>
</html>