1.随机整数
Math.floor()向下取整,Math.random()随机数0~1,
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min
}
可以获取随机整数
2.定时器
setInterval(function() { },interave)间隔定时器
settimeout(function() { },interave)倒计时定时器
3.实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;padding: 0;
list-style: none;
}
div{
width: 500px;
margin: 0 auto;
}
h1{
height: 70px;
background-color: honeydew;
}
#list .seclect{
background-color: pink;
}
#list .active{
background-color: goldenrod;
}
#list li{
float: left;
margin:5px 5px;
width: 80px;
text-align: center;
line-height: 40px;
height: 40px;
background-color: gray;
}
</style>
</head>
<body>
<div>
<h1 id="h1">被选中</h1>
<button id="btn">开始</button>
<button id="btl">暂停</button>
<ul id="list"></ul>
</div>
<script>
var arr=["张三","李四","王五","克六","乔治","威少","杜兰特","詹姆斯","保罗","库里","欧文","汤普森"]
for(var i=0;i<arr.length;i++){
var oli=document.createElement("li")
oli.innerHTML=`${arr[i]}`
list.append(oli)
}
var lp
var oli1=document.querySelectorAll("li")
console.log(oli1)
btn.onclick=function(){
clearInterval(lp)
timl()
}
function timl(){
lp= setInterval(function() {
var lac=document.querySelector("li.active")
lac && lac.classList.remove("active")
// 避免重复选择
var kk=document.querySelectorAll("li:not(.seclect)")
var index = getRandom(0,kk.length-1)
kk[index].classList.add("active")
}, 100);
}
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min
}
btl.onclick=function(){
clearInterval(lp)
var selet=document.querySelector("li.active")
selet.classList.add("seclect")
selet.classList.remove("active")
h1.innerHTML+=" " +selet.innerHTML
}
</script>
</body>
</html>