萬盛學電腦網

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

jQuery 打造果凍抖動效果:animate() 連續縮放實作

效果預覽

滑鼠移入綠色方塊 → 寬高放大 → 微微縮小回彈 → 移出 → 恢復原尺寸。類似果凍般的彈性視覺回饋。

完整範例

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(function() {
      $("div.jelly").hover(
        function() { // mouseenter
          $(this).stop(true) // 停止當前動畫,清除佇列
            .animate({ width: "320px", height: "100px" }, 100)
            .animate({ width: "310px", height: "90px" }, 100);
        },
        function() { // mouseleave
          $(this).stop(true)
            .animate({ width: "300px", height: "80px" }, 100);
        }
      );
    });
  </script>
  <style>
    .jelly {
      width: 300px; height: 80px;
      border-radius: 8px; background: #27ae60;
      margin-top: 10px;
    }
    body { background: #e8e8e8; padding: 20px; }
  </style>
</head>

  

核心技術解析

關鍵點說明
.stop(true)**關鍵**:`true` = 清除動畫佇列,防止快速進出導致動畫疊加抖動
鏈式 animate依序執行:放大 → 縮小回彈,形成「過衝」果凍感
數值單位寬高需帶單位 (`px`),或用數字 (jQuery 內部轉 px)
持續時間100ms 快速切換,太久會感覺遲鈍,太短無回彈感

進階:更真實的彈性動畫 (jQuery UI / CSS)

原生 `animate` 只能線性/緩動,無法做真正的彈簧物理。推薦方案:

方案一:CSS Transition + Transform (效能最佳)

<style>
.jelly-css {
  width: 300px; height: 80px; border-radius: 8px; background: #27ae60;
  transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55); /* 超出邊界的貝茲曲線 = 彈性 */
  transform-origin: center center;
}
.jelly-css:hover { transform: scale(1.08); }
</style>

<div class="jelly-css"></div>

`cubic-bezier(0.68, -0.55, 0.27, 1.55)` 是經典「彈性」曲線 (y1<0, y2>1 產生過衝)。

方案二:jQuery UI `.effect("bounce")`

<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
$(".box").mouseenter(function() {
  $(this).effect("bounce", { times: 2, distance: 10 }, 300);
});

方案三:GSAP (專業動畫庫)

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
gsap.to(".box", { scale: 1.1, duration: 0.3, ease: "back.out(1.7)", paused: true });
// 滑鼠事件控制 play/reverse

適用場景比較

方案適用場景依賴效能
jQuery animate 連續縮放簡單專案、無額外依賴限制jQuery中 (觸發 layout 重排)
CSS transform + cubic-bezier現代專案、追求 60fps、無 JS 依賴無極佳 (GPU 加速)
GSAP複雜時間軸、專業動畫需求GSAP極佳

總結

  • 原文範例展示了 `animate` 串聯產生果凍感的基本思路。
  • **務必加 `.stop(true)`** 避免動畫佇列堆疊。
  • 現代開發**強烈建議改用 CSS `transform: scale()` + `transition`**,效能更好、程式碼更少、無閃爍風險。
  • 理解「過衝」原理(超過目標值再回彈)是設計彈性動畫的關鍵。
copyright © 萬盛學電腦網 all rights reserved