简单小例子,1到10随机数。

1到10随机数展示,可暂停继续,空格控制。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title></title>
	
</head>
<body style="text-align:center;background:#ccc;padding-top:100px;">
	<h2 id="box">0</h2>
	<button id="stop">停止</button>
	<button id="continue">继续</button>
	<p>记录:</p>
	<ul id="ul" style="width:100px;margin: 0 auto;"></ul>
	<script>
		;(function(){
			var remark = false;
			var s = setInterval(rand,30);		
			function rand(){  //随机函数
				var m = parseInt(Math.random() * 10) + 1;
				gets("box").innerHTML = m;
			}
			function gets(str){  //根据id获取元素
				return document.getElementById(str);
			}
			function getBoxText(){  //获取box的值
				return gets("box").innerHTML;
			}
			function setLiText(t){  //在ul中记录值
				var li = document.createElement("li");
				li.innerHTML = t;
				gets("ul").appendChild(li);
			}		
			gets("continue").onclick = continueRandom;
			function continueRandom(){	//继续
				if(!s){
					s = setInterval(rand,30);
				}
				remark = false;		
				this.blur();
			};
			gets("stop").onclick = stopRandom;
			function stopRandom(){	//停止
				clearInterval(s);
				s = null;
				if(!remark){
					setLiText(getBoxText());
					remark = true;
				}
				this.blur();
			};
			document.onkeyup = function(event){  //空格键
				event = event || window.event;
				if(event.keyCode === 32 && s){
					stopRandom();
				}else if(event.keyCode === 32 && !s){
					continueRandom();
				}
			};
			
			
		})()	
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qiuqidehao/article/details/80582437