js 随机点名 和 js生成随机数
方式一 两个按钮的随机点名 案例
<script type="text/javascript">
var startID=null;
function startName() {
var arr = [
"隔壁老王",
"东方不败",
"西门吹雪",
"欧阳无敌",
"司马不平",
"上官雪儿",
"纳兰容若"
]
var randomNum = Math.floor(Math.random() * 7);
var showID= document.getElementById("showName");
var showName = arr[randomNum];
showID.innerHTML = showName;
document.getElementById("startName").disabled=true;
startID = setTimeout("startName();", 50);
}
function endName() {
document.getElementById("startName").disabled=false;
clearTimeout(startID)
}
</script>
</head>
<body>
<center>
<div id="showName" style="margin-top: 100px; color: red; font-size: 30px;" >请点击开始 </div>
<hr />
<button onclick="startName();" id="startName" style="font-size: 20px; color: darkmagenta;">开始点名</button>
<button onclick="endName()" id="endName" style="font-size: 20px; color: darkmagenta;">结束点名</button>
</center>
</body>
方式二 单个按钮的随机点名 案例
<script type="text/javascript">
var startID = null;
function btnName() {
var btnID = document.getElementById("startName");
var textVaule = btnID.firstChild.nodeValue;
if(textVaule == "开始点名") {
btnID.innerHTML = "停止点名";
startName();
} else if(textVaule == "停止点名") {
btnID.innerHTML = "开始点名";
clearTimeout(startID);
}
}
function startName() {
var arr = [
"隔壁老王",
"东方不败",
"西门吹雪",
"欧阳无敌",
"司马不平",
"上官雪儿",
"纳兰容若"
]
var randomNum = Math.floor(Math.random() * 7);
var showID = document.getElementById("showName");
var showName = arr[randomNum];
showID.innerHTML = showName;
startID = setTimeout("startName();", 50);
}
</script>
</head>
<body>
<center>
<div id="showName" style="margin-top: 100px; color: red; font-size: 30px;">请点击开始 </div>
<hr />
<button onclick="btnName();" id="startName" style="font-size: 20px; color: darkmagenta;">开始点名</button>
</center>
</body>
生成随机数 案例
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var startID = null;
function btnName() {
var btnID = document.getElementById("btn");
var textVaule = btnID.value;
if(textVaule == "生成随机数") {
btnID.value = "停止";
btn();
} else if(textVaule == "停止") {
btnID.value = "生成随机数";
clearTimeout(startID);
}
}
function btn(){
var randomNum=Math.floor(Math.random()*900000)+100000;
var showID=document.getElementById("show");
showID.value=randomNum;
startID=setTimeout("btn()",100);
}
</script>
</head>
<body>
<center>
<div style="border: 10px solid gainsboro; align-content: center; width: 200px; height: 100px; margin-top: 200px;" >
<input type="text" name="textValue" id="show" style="margin-top: 20px; text-align: center;"/> <br /><br />
<input type="button" id="btn" onclick="btnName()" value="生成随机数" />
</div>
</center>
</body>