Js取任意范圍的隨機數并在html中動態顯示
如下效果:
相關代碼如下:
<div id="setnum03" class="number">---</div> <script type="text/javascript"> setInterval(displayNum3,1000); function displayNum3() { document.getElementById("setnum03").innerHTML = Math.floor(Math.random() * (31 - 25) + 25) + ' °C'; } </script><div class="desc"> 當前溫度 </div>
1.取任意范圍的隨機數:
Math.floor(Math.random() * (31 - 25) + 25)
上面是我的,大家都知道Math.random()會生成一個0-1的隨機數。,通過下面這個公司就能夠獲得設定范圍的隨機數了...
Math.random() * (max - min) + min
再來做一個向下取舍,去整數。
Math.floor(Math.random() * (max - min) + min)
2.動態刷新:
每間隔一秒調用一次函數
setInterval(displayNum3,1000);
新聞熱點
疑難解答