萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作動態「飄過」文字特效

效果預覽

文字在畫面水平來回移動,形成「飄過」視覺效果,適合用於簡單的跑馬燈或裝飾動畫。

完整 HTML + JS 範例

<!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>

原理解析

  1. 使用 setInterval 每 80ms 重繪畫面。
  2. 外層迴圈產生 _y 行,每行的縮排位置 pos 依方向 direcation 遞增/遞減。
  3. 碰到邊界(0 或 _x)反轉方向。
  4. repeat 函式利用 Array.join 快速產生重複字串。

擴充建議

  • 將文字、速度、範圍參數化,封裝成 jQuery 外掛。
  • 改用 CSS animation 或 transform: translateX 可獲得更流暢效能。
copyright © 萬盛學電腦網 all rights reserved