點擊此處查看DEMO演示javascript
今天在作大衆點評在線筆試題目的時候,遇到一個頗有趣的編程題目,實現黑客電影中的字符串效果。css
對!就是圖中這樣……當時是直接在提交文本框上寫的,也沒有調試機會,因而確定會有很bug,晚上閒來無事,從新實現一下~html
<!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>