萬盛學電腦網

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

jQuery animate() 實現元素平滑移動:從定位原理到實戰動畫

核心前提:CSS 定位是前提

.animate() 只能改變 已定位元素 的位置屬性(top/left/right/bottom/margin 等)。元素的 CSS position 必須是 relative、absolute 或 fixed,static(預設)無效。

基礎範例:水平移動

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>animate 移動示例</title>
  <style>
    #box {
      width: 100px; height: 100px;
      background: #27ae60;
      position: absolute; /* 關鍵! */
      left: 0; top: 50px;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <button id="btn-move">開始移動</button>
  <p>注意:元素必須設定 position: relative/absolute/fixed 才能移動</p>
  <div id="box"></div>

  <script>
    $('#btn-move').click(function() {
      $('#box').animate({ left: '250px' }, 1000); // 1 秒內移動到 left:250px
    });
  </script>
</body>
</html>

animate() 完整語法

.animate(properties [, duration] [, easing] [, complete])
// properties: { left: '250px', opacity: 0.5, height: 'toggle' }
// duration: 毫秒數 | 'fast'(200) | 'slow'(600) | 預設 400
// easing: 'swing' (默認) | 'linear' | 自定義 easing 函數
// complete: 動畫完成回調 function() {}

進階動畫屬性

屬性類型示例說明
位置 { left: '+=50', top: '-=20' } 相對當前值增減(+=/-=)
尺寸 { width: '300px', height: 'toggle' } show/hide/toggle 關鍵字
透明度 { opacity: 0.3 } 0~1,跨瀏覽器兼容
邊距/內距 { marginLeft: '20px', padding: '10px' } 需帶單位
顏色 { backgroundColor: '#fff' } 需引入 jQuery Color 插件 或使用 CSS transition
滾動 { scrollTop: 500 } 作用於可滾動容器

鏈式與隊列控制

// 順序執行(默認進隊列)
$('#box')
  .animate({ left: '200px' }, 500)
  .animate({ top: '100px' }, 500)
  .animate({ opacity: 0 }, 300);

// 並行執行(queue: false)
$('#box').animate({ left: '200px' }, { duration: 500, queue: false })
        .animate({ top: '100px' }, { duration: 500, queue: false });

// 回調地獄替代:Promise/async-await (jQuery 3.0+)
await $('#box').animate({ left: '200px' }).promise();
await $('#box').animate({ top: '100px' }).promise();
console.log('動畫序列完成');

停止與控制

// 停止當前動畫,跳到終態
$('#box').stop(true, true); // clearQueue=true, jumpToEnd=true

// 僅停止當前動畫,保留隊列
$('#box').stop(false, false);

// 暫停/恢復(需 jQuery Pause 插件或自行實現)

性能優化建議

  • 優先用 CSS transform:transform: translateX(250px) 觸發 GPU 加速,不觸發重排。jQuery 可動畫 { transform: 'translateX(250px)' }(需 jQuery 3.0+ 或插件)。
  • 避免動畫高度/寬度:觸發佈局重排,改用 transform: scale() 或 max-height 技巧。
  • 使用 requestAnimationFrame 替代:複雜高性能動畫建議原生 Web Animations API 或 GSAP。
  • will-change 提示瀏覽器:.will-animate { will-change: transform, opacity; }。

實戰場景:模態框彈出動畫

function showModal($modal) {
  $modal.css({ opacity: 0, top: '-50px', display: 'block' })
        .animate({ opacity: 1, top: '50%' }, 300, 'swing');
}

function hideModal($modal) {
  $modal.animate({ opacity: 0, top: '150%' }, 200, function() {
    $(this).hide();
  });
}

總結

jQuery .animate() 提供了聲明式、鏈式、隊列化的動畫能力,核心前提是 CSS 定位。現代開發中,簡單位移/透明度動畫首選 CSS Transition/Animation(性能更好、可硬體加速);複雜序列、動態計算、舊專案維護時,.animate() 依然是高效選擇。理解其隊列機制、停止控制、與 CSS 動畫的取捨,是前端動畫工程化的關鍵。

copyright © 萬盛學電腦網 all rights reserved