js 隨機數代碼大全
更新時間:2010年08月20日 15:26:51 作者:
很多情況下,需要用到隨機數,腳本之家特為大家整理了一些具體的使用與說明。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
引用部分:
1. 從1開始 至 任意值
parseInt(Math.random()*上限+1);
2. 從任意值開始 至 任意值
parseInt(Math.random()*(上限-下限+1)+下限);
function fRandomBy(under, over){
switch(arguments.length){
case 1: return parseInt(Math.random()*under+1);
case 2: return parseInt(Math.random()*(over-under+1) + under);
default: return 0;
}
}
document.write(fRandomBy(1,100)); //輸出指定范圍內的隨機數的隨機整數
</script>
下面是給文本框按規(guī)則付不同的隨即值[引申]
復制代碼 代碼如下:
1-10: <input type="text" /><br />
11-20: <input type="text" /><br />
1-100: <input type="text" /><br />
51-100: <input type="text" /><br />
<script>
window.onload=function(){
var o=document.getElementsByTagName('input');
o[0].value=fRandomBy(1,10);
o[1].value=fRandomBy(11,20);
o[2].value=fRandomBy(1,100);
o[3].value=fRandomBy(51,100);
}
</script>
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
相關文章
open 動態(tài)修改img的onclick事件示例代碼
動態(tài)修改img的onclick事件,使用open也可輕松做到,下面有個不錯的示例,需要的朋友可以參考下2013-11-11