js用math函数实现伪随机点名效果

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			body {
				text-align: center;
			}

			h2 {
				font-size: 50px;
				color: #00ADEF;
				padding: 200px 0 50px;
			}

			button {
				font-size: 20px;
				background: none;
				border: none;
				outline: none;
				cursor: pointer;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				var txt = document.querySelector('h2');
				var btn = document.querySelector('button');
				// console.log(txt,btn);
				var arr = [];
				//初始化人名
				for (var i = 0; i < 20; i++) {
					arr.push('代' + i + '豪');
				}
				// console.log(arr);
				// console.log(name);
				var onoff = true;
				var timer = null;
				btn.onclick = function() {
					clearInterval(timer);
					if (onoff) {
						timer = setInterval(function() {
							// Math.random() 范围 [0.1),以下三种方法均可
							// var num = Math.round(Math.random() * (arr.length - 1));
							// var num = parseInt(Math.random() * (arr.length));
							var num = Math.floor(Math.random() * (arr.length));
							// console.log(arr[num]);
							txt.innerText = arr[num];
						}, 60);
						btn.innerText = '暂停';
					} else {
						btn.innerText = '开始点名';
					}
					onoff = !onoff;
				}
			}
		</script>
	</head>
	<body>
		<h2>点击开始点名</h2>
		<button type="button">开始点名</button>
	</body>
</html>

 

posted @ 2020-03-28 15:22  JackieDYH  阅读(7)  评论(0编辑  收藏  举报  来源