应用场景:设置一个范围,然后随机显示出这个范围里面的数字。在一定的时间里面这个随机数不断的变化,直到时间结束,最终显示出最后的数字。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>随机数生成</title>
<style type="text/css">
.box{
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.inputNum{
margin-top: 100px;
}
.circle{
width: 300px;
height: 300px;
background-color: #41a863;
margin-top: 50px;
display: flex;
align-items: center;
justify-content: center;
}
.circle span{
color: #fff;
font-size: 150px;
font-weight: 700;
}
.anniu{
margin-top: 20px;
}
</style>
</head>
<body>
<div class="box">
<div class="inputNum">
<span>输入随机数范围</span>
<input type="text" name="minNum" id="minNum" placeholder="输入最小值"/>
<input type="text" name="maxNum" id="maxNum" placeholder="输入最大值"/>
</div>
<div class="circle">
<span id="num"></span>
</div>
<div class="anniu">
<button type="button" onclick="begin()">开始</button>
</div>
</div>
</body>
<script type="text/javascript">
let minNum = document.getElementById('minNum')
let maxNum = document.getElementById('maxNum')
let num = document.getElementById('num')
var beginTime
let setNum = 3
// 点击开始
function begin(){
clearInterval(timeEnd)
clearInterval(beginTime) //在程序开始前清空所有的定时器,防止连续多次点击按钮出现定时器错误
if(minNum.value !== '' && maxNum.value !== ''){
var timeEnd = setInterval(function(){
setNum--
if(setNum == 0){ //当倒计时结束时把定时器清空,值返回原值
clearInterval(timeEnd)
clearInterval(beginTime)
setNum = 3
}else{
clearInterval(beginTime) //清理定时器
beginTime = setInterval("getNum(minNum.value,maxNum.value)",150)
}
},1000)
}else{
alert('输入取值范围')
}
}
function getNum(minNum,maxNum){
minNum = parseInt(minNum)
maxNum = parseInt(maxNum)
let num1 = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum //在规定范围里面出随机数
num.innerHTML = num1
}
</script>
</html>