萬盛學電腦網

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

原生 JS 實現彈窗抖動特效:無限變色 + 震動動畫完整代碼

純原生 JS 實現點擊觸發的彈窗抖動效果,結合隨機背景色變化,展示定時器、動畫幂、樣式操作綜合應用。

效果預覽

  • 點擊方塊 → 水平抖動 → 垂直抖動 → 顯示當前背景色
  • 同時另一定時器每 130ms 隨機變換背景色

完整代碼(單文件可運行)

<!doctype html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>彈窗抖動特效</title>
  <style>
    .box {
      width: 300px; height: 150px;
      position: absolute;
      text-align: center; line-height: 150px;
      font-weight: bold; cursor: pointer;
    }
    #dv  { left: 200px; top: 100px; background: red; }
    #dv2 { left: 600px; top: 100px; background: yellow; }
  </style>
</head>
<body>
  <div id="dv" class="box">點我呀</div>
  <div id="dv2" class="box">點我呀</div>

  <script>
    window.onload = function() {
      // 工具:隨機整數 [min, max]
      const rand = (min, max) => min + Math.round(Math.random() * (max - min));

      // 獲取元素
      const dv  = document.getElementById('dv');
      const dv2 = document.getElementById('dv2');

      // 抖動位移序列:20, -20, 18, -18 ... 2, -2
      const shakeOffsets = [];
      for (let i = 20; i > 0; i -= 2) {
        shakeOffsets.push(i, -i);
      }

      // 1. 隨機變色定時器
      setInterval(() => {
        const color = `rgb(${rand(0,255)}, ${rand(0,255)}, ${rand(0,255)})`;
        dv.style.backgroundColor = color;
      }, 130);

      // 2. 通用抖動函數
      function shake(el, attr, onEnd) {
        let index = 0;
        const startVal = parseInt(getComputedStyle(el)[attr]);
        const timer = setInterval(() => {
          if (index >= shakeOffsets.length) {
            clearInterval(timer);
            onEnd?.();
            return;
          }
          el.style[attr] = startVal + shakeOffsets[index] + 'px';
          index++;
        }, 50);
      }

      // 3. 獲取樣式兼容封裝
      function getStyle(el, prop) {
        return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el)[prop];
      }

      // 4. 綁定點擊:先左抖動,再上抖動,最後顯示顏色
      [dv, dv2].forEach(box => {
        box.onclick = () => {
          shake(box, 'left', () => {
            shake(box, 'top', () => {
              box.innerHTML = `我是${getStyle(box, 'backgroundColor')}色`;
            });
          });
        };
      });
    };
  </script>
</body>
</html>

核心技術點解析

  1. 抖動軌跡設計:對稱遞減位移數組 [20,-20,18,-18,...,2,-2] 模擬物理阻尼效果。
  2. 串聯動畫:回調函數 onEnd 實現水平→垂直→文本更新的序列執行。
  3. 樣式讀取兼容:currentStyle (IE) vs getComputedStyle (標準)。
  4. 隨機色生成:rgb(r,g,b) 格式,每通道 0-255。

擴展建議

  • 用 requestAnimationFrame 替換 setInterval 獲得更流暢動畫。
  • 提取抖動邏輯為通用工具函數 shakeElement(el, {x: true, y: true})。
  • 添加 CSS transition 實現平滑過渡(需配合 transform 而非 left/top)。

總結

本例展示了原生 JS 實現視覺特效的完整思路:數據驅動動畫(位移數組)、狀態機控制流程(回調串聯)、兼容性封裝。理解此模式,可輕鬆構建各類交互動畫。

copyright © 萬盛學電腦網 all rights reserved