DIV CSS 佈局教程網

用 JS 做出氣泡由下往上急速上升的效果
編輯:關於JavaScript     

這個範例用 JavaScript 建立一批 <img> 元素當作氣泡,讓它們從畫面下方持續往上飄,並在接近滑鼠游標時被「吸」過去。屬於早期 DHTML 時代的經典視覺特效。

範例

<html>
<head>
<title>JS 實現氣泡從水中急速上升效果</title>
<style type="text/css">
body {
    cursor: crosshair;
    margin: 0;
    padding: 0;
    position: absolute;
    overflow: hidden;
    background: #FFF;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
</style>

<script type="text/javascript">
var object = new Array();
var nbfm = 60;          // 氣泡數量
var xm = 0, ym = 9999;  // 滑鼠座標
var nx = 0, ny = 0;     // 視窗尺寸

function movbulb() {
    with (this) {
        // 游標附近 100px 內時,逐漸被吸過去
        if (ec < 20) {
            if (Math.abs(x0 - xm) < 100 && Math.abs(y0 - ym) < 100) {
                xx = (xm - x0) / 8;
                yy = (ym - y0) / 8;
                ec++;
            }
        }

        // 阻尼:速度逐格衰減
        xx *= 0.99;
        yy *= 0.99;

        x0 = Math.round(x0 + Math.cos(y0 / 15) * p) + xx;   // 左右擺盪
        y0 += yy - v;                                       // 向上飄

        // 超出畫面就從底部重生
        if (y0 < -h * 2 || x0 < -w * 2 || x0 > nx + w * 2) {
            y0 = ny + N + h * 2;
            x0 = nx / 2 - 100 + Math.random() * 100;
            ec = 0;
        }

        obj.style.top  = y0 - h;
        obj.style.left = x0 - w;
    }
}

function CObj(N, img, w, h) {
    this.obj = document.createElement("img");
    this.obj.src = img.src;
    this.obj.style.position = "absolute";
    this.obj.style.left = -1000;
    document.body.appendChild(this.obj);

    this.N  = N;
    this.x0 = 0;
    this.y0 = -1000;
    this.v  = 1 + Math.round((80 / h) * Math.random());   // 上升速度
    this.p  = 1 + Math.round((w / 8) * Math.random());    // 擺盪幅度
    this.xx = 0;
    this.yy = 0;
    this.ec = 0;
    this.w  = w;
    this.h  = h;
    this.movbulb = movbulb;
}

function resize() {
    nx = document.body.offsetWidth;
    ny = document.body.offsetHeight;
}
onresize = resize;

document.onmousemove = function (e) {
    if (window.event) e = window.event;
    xm = document.body.scrollLeft + (e.x || e.clientX);
    ym = document.body.scrollTop  + (e.y || e.clientY);
};

function run() {
    for (var i in object) object[i].movbulb();
    setTimeout(run, 16);      // 約 60fps
}

onload = function () {
    var PIC = document.getElementById("bubbles").getElementsByTagName("img");
    resize();
    for (var nbf = 0; nbf < nbffm; nbf++) {
        var sf = PIC[nbf % PIC.length];
        object[nbf] = new CObj(nbf, sf, sf.width / 2, sf.height / 2);
    }
    run();
};
</script>
</head>

<body>
<div id="bubbles" style="visibility:hidden">
  <img src="https://bbs.blueidea.com/static/image/smiley/blueidea/smile.gif">
  <img src="https://bbs.blueidea.com/static/image/smiley/blueidea/biggrin.gif">
  <img src="https://bbs.blueidea.com/static/image/smiley/blueidea/eek.gif">
  <img src="https://bbs.blueidea.com/static/image/smiley/blueidea/rolleyes.gif">
</div>
</body>
</html>

動畫的三個組成部分

  1. 持續上升:y0 += yy - v,v 是每個氣泡各自隨機的上升速度,讓整體有快慢層次。
  2. 左右擺盪:Math.cos(y0 / 15) * p 用餘弦函式模擬水中搖曳,因為 cos 的值域固定在 ±1,氣泡不會飄出畫面。
  3. 阻尼與吸附:游標靠近時依距離的 1/8 給一個速度,之後每格乘上 0.99 逐漸衰減,形成自然的減速。

原範例的問題與現代改寫

這段程式碼有幾個明顯缺陷:nbfm 與迴圈中的 nbffm 拼字不一致會直接報錯;大量使用 with(嚴格模式下禁用);用全域 onload/onmousemove 會覆蓋其他程式碼;60 個元素的 setTimeout 鏈效能不佳。

現代做法是改用 CSS animation 讓瀏覽器合成器處理位移,再用 requestAnimationFrame 統一驅動:

.bubble {
    position: fixed;
    bottom: -40px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: rgba(120, 190, 255, 0.5);
    animation: rise linear infinite;
    will-change: transform;
}

@keyframes rise {
    from { transform: translateY(0) translateX(0); }
    50%  { transform: translateY(-50vh) translateX(20px); }
    to   { transform: translateY(-110vh) translateX(-10px); }
}
(function () {
    var layer = document.getElementById('bubbleLayer');
    var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;                     // 尊重使用者偏好

    for (var i = 0; i < 30; i++) {
        var b = document.createElement('div');
        b.className = 'bubble';
        b.style.left = Math.random() * 100 + 'vw';
        b.style.animationDuration = (6 + Math.random() * 6) + 's';
        b.style.animationDelay = (-Math.random() * 12) + 's';   // 負值可讓動畫錯開
        b.style.opacity = 0.3 + Math.random() * 0.4;
        layer.appendChild(b);
    }
})();

用 transform 而非 top/left,動畫在 GPU 上跑,不會觸發重排;animation-delay 設為負值可以讓所有氣泡的相位錯開,不必等第一段跑完。若要加入游標吸附,只需在 pointermove 中更新 CSS 變數 --mx/--my,讓 keyframes 引用即可。

最後提醒:這類全螢幕裝飾動畫會持續消耗 CPU/GPU 與電力,行動裝置上尤其明顯。建議限制數量、在 visibilitychange 時暫停,並務必提供 prefers-reduced-motion 的關閉路徑。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved