這個效果的原理並不難:每一列文字前面補上不同數量的點,讓「飄過」兩個字的位置逐列位移,再用 setInterval 定時重繪,看起來就像一群字隨機飄動。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
// 初始化
var _pos = 0; // 初始位置
var _direcation = 1; // 初始方向,1 為 x+ 方向,-1 為 x- 方向
var _x = 5; // 最大寬度
var _y = 40; // 最大高度
// 動態更新
function update(){
var pos = _pos; // 當前位置
var direcation = _direcation; // 當前方向
var output = '';
for(var i=0; i<_y; i++){
output += '<div>' + rp('.',pos) + '飄過</div>';
if((pos<=0 && direcation<=0) || (pos>=_x && direcation>=0))
direcation *= -1; // 更新方向
pos += direcation * 1; // 更新位置
}
$('#happy').html(output);
// 更新初始數據
if((_pos<=0 && _direcation<=0) || (_pos>=_x && _direcation>=0))
_direcation *= -1; // 更新方向
_pos += _direcation * 1; // 更新位置
}
// 重複輸出字串 N 次
function rp(str,len){
return new Array(len+1).join(str);
}
</script>
<style type="text/css">
body,html{font-size:12px; letter-spacing: 0.2em;}
div{margin:5px 20px;}
</style>
</head>
<body>
<div id="happy"></div>
<script type="text/javascript">
setInterval('update()',80);
</script>
</body>
</html>
幾個可以拿來微調的地方:_x 控制水平位移範圍,_y 決定輸出幾列,setInterval 的 80 毫秒則是刷新節奏,數值越小跑越快。另外 rp() 用 new Array(len+1).join(str) 來重複字串,比迴圈拼接乾淨得多。
若在意效能,建議把字串組裝好再一次寫入 DOM(如本例),避免在迴圈裡反覆操作節點。