假装成黑客

点击此处查看DEMO演示

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!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>