文字在畫面水平來回移動,形成「飄過」視覺效果,適合用於簡單的跑馬燈或裝飾動畫。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery.min.js"></script>
<style>
body,html{font-size:12px; letter-spacing: 0.2em;}
div{margin:5px 20px; font-family: monospace;}
</style>
</head>
<body>
<div id="happy"></div>
<script>
var _pos = 0, _direcation = 1, _x = 5, _y = 40;
function update() {
var pos = _pos, direcation = _direcation, output = '';
for (var i = 0; i < _y; i++) {
output += '<div>' + repeat('.', 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;
}
function repeat(str, len) {
return new Array(len + 1).join(str);
}
setInterval(update, 80);
</script>
</body>
</html>
setInterval 每 80ms 重繪畫面。_y 行,每行的縮排位置 pos 依方向 direcation 遞增/遞減。_x)反轉方向。repeat 函式利用 Array.join 快速產生重複字串。animation 或 transform: translateX 可獲得更流暢效能。