假装成黑客

点击此处查看DEMO演示

今天在做大众点评在线笔试题目的时候,遇到一个很有趣的编程题目,实现黑客电影中的字符串效果。

对!就是图中这样……当时是直接在提交文本框上写的,也没有调试机会,于是肯定会有很bug,晚上闲来无事,重新实现一下~

<!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>Document</title>
	<style type="text/css">
		body {
			background: #000;
			color: #fff;
		}
		.rain {
			position: absolute;
			top: 0;
			left: 0;
			font-size: 20px;
			background: lightgreen;
			width: 25px;
			box-shadow: 2px 2px 4px green;
		}
	</style>
</head>
<body>
	<!-- <div class="rain"></div> -->
	<script type="text/javascript">
		function generateChar() {
			var strLen = Math.floor(Math.random()*100);
			var i = 0;
			var choose = 0;
			var resCode = 0;
			var str = '';
			for (i = 0; i < strLen; i++) {
				choose = Math.floor(Math.random()*3);
				switch (choose) {
					case 0:
						resCode = Math.floor(Math.random()*10 + 48);
						break;
					case 1:
						resCode = Math.floor(Math.random()*26 + 65);
						break;
					case 2:
						resCode = Math.floor(Math.random()*26 + 97);
						break;
				}
				str += String.fromCharCode(resCode)+'<br>';
			}
			return str;
		}

		function animate(obj) {
			var cWidth = document.documentElement.clientWidth-10;
			var cHeight =  document.documentElement.clientHeight;
			// alert(cHeight);
			var startLeft = Math.floor(Math.random()*cWidth);
			var startTop = 0;
			obj.style.left = startLeft + 'px';
			obj.style.top = startTop + 'px';
			var speed = 10;

			obj.timer = setInterval(function(){
				startTop += speed;
				obj.style.top = startTop + 'px';
				if (startTop > cHeight-obj.offsetHeight) {
					clearInterval(obj.timer);
					document.body.removeChild(obj);
				}
			}, 30);
		}

		setInterval(function(){
			var obj = document.createElement('div');
			obj.className = 'rain';
			obj.innerHTML = generateChar();
			document.body.appendChild(obj);
			animate(obj);
		}, 50);
		
	</script>
</body>
</html>
posted @ 2015-09-17 23:26  钟山  阅读(1424)  评论(0编辑  收藏  举报