
js 实现一个随机点名
JavaScript实现一个随机点名,用到定时器和数组和随机数。
·
实现原理:一个显示名字的div,两个按钮,点击一个按钮的时候通过一个随机数组函数和定时器(setInterval)每隔50毫毛变换一次。把先换的结果显示到div里面。点击另一个按钮的时候停止定时器(clearInterval)。
<!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></title>
<style>
div {
width: 200px;
height: 60px;
font-size: 20px;
border: 1px solid rgb(126, 123, 120);
background-color: rgb(37, 228, 139);
text-align: center;
line-height: 60px;
margin: 0 auto;
}
button {
width: 98px;
height: 30px;
text-align: center;
line-height: 30px;
}
p {
text-align: center;
}
</style>
</head>
<body>
<div>开始点名!</div>
<p>
<button id="start">点名开始</button>
<button id="end">点名结束</button>
</p>
</body>
<script>
// 获取元素
var box = document.querySelector('div');
var btn_start = document.querySelector('#start');
var btn_end = document.querySelector('#end');
var timer;
//名字数组
let arr = ['阿珍', '函数', '乔峰', '阿强', '小青', '啊假', '眼睛蛇', '大轮明王', '郭靖', '李刚', '鸠摩智', '扫地僧', '紫嫣'];
// 生成随机名字
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 开始
btn_start.addEventListener('click', function () {
//防止多点
clearInterval(timer)
timer=setInterval(()=>{
let random = getRandom(0, arr.length - 1);
box.innerHTML = arr[random];
},50)
})
// 结束
btn_end.addEventListener('click', function () {
clearInterval(timer)
})
</script>
</html>
效果
点击阅读全文
更多推荐
活动日历
查看更多
直播时间 2025-02-26 16:00:00


直播时间 2025-01-08 16:30:00


直播时间 2024-12-11 16:30:00


直播时间 2024-11-27 16:30:00


直播时间 2024-11-21 16:30:00


所有评论(0)