萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

jQuery 實現天貓級拋物線加入購物車動畫:jquery.fly.min.js 實戰教程

電商項目中,「加入購物車」的拋物線飛入動畫能顯著提升操作反饋感與轉化率。本文基於 jquery.fly.min.js 插件,手把手實現與天貓、聚美優品一致的頂級交互體驗。

效果預覽

加入購物車拋物線動畫演示

準備工作

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="jquery.fly.min.js"></script>
<!-- IE10- 需補 requestAnimationFrame polyfill -->
<!--[if lte IE 10]>
<script src="requestAnimationFrame.js"></script>
<![endif]-->

HTML 結構

<div class="demo clearfix">
  <div class="per">
    <img src="images/1.jpg" width="180" height="240" alt="商品圖片" />
    <h3>¥<span>259.00</span></h3>
    <div class="title">春款真皮坡跟大碼單鞋</div>
    <a href="javascript:void(0);" class="button orange addcart">加入購物車</a>
  </div>
  <!-- 更多商品項... -->
</div>

<!-- 購物車圖標(目標點) -->
<div id="icon-cart" class="cart-icon">🛒</div>
<div id="tip" class="tip-box">加入成功!</div>

核心 JS 邏輯

$(function() {
  // 目標元素位置(購物車圖標)
  const $cart = $('#icon-cart');
  const offset = $cart.offset(); // { left, top }

  $('.addcart').on('click', function(event) {
    const $btn = $(this);
    const $product = $btn.closest('.per');
    const imgSrc = $product.find('img').attr('src');

    // 創建飛行元素(縮放後的商品圖)
    const $flyer = $('');
    $('body').append($flyer); // 必須加入 DOM 才能獲取座標

    // 配置拋物線動畫
    $flyer.fly({
      start: {
        left: event.pageX, // 以點擊位置為起點
        top: event.pageY
      },
      end: {
        left: offset.left + 10, // 終點微調
        top: offset.top + 10
      },
      onEnd: function() {
        // 成功反饋動畫
        $('#tip').show().animate({ width: '200px' }, 300).fadeOut(500);
        // 銷毀飛行元素
        this.destroy();
      }
    });
  });
});

關鍵點解析

  1. 起點座標:使用 event.pageX/Y 獲取點擊位置,視覺上從按鈕處「飛出」;
  2. 終點座標:目標元素 offset() + 微調偏移,確保落入圖標中心;
  3. 飛行元素:動態創建 <img>,設置 position: absolute; z-index: 9999; pointer-events: none;(插件內部處理);
  4. 銷毀機制:this.destroy() 移除 DOM、清理定時器,防止內存洩漏;
  5. IE 兼容:舊 IE 缺乏 requestAnimationFrame,需引入 polyfill。

CSS 關鍵樣式(建議)

.flyer-img {
  position: absolute;
  width: 50px; height: 50px;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0,0,0,.3);
  pointer-events: none;
  z-index: 9999;
}
.cart-icon {
  position: fixed;
  right: 20px; bottom: 20px;
  width: 50px; height: 50px;
  background: #ff6b35;
  border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: 24px; color: #fff;
  cursor: pointer;
}
.tip-box {
  display: none;
  position: fixed;
  right: 80px; bottom: 30px;
  background: #ff6b35; color: #fff;
  padding: 8px 16px; border-radius: 20px;
  white-space: nowrap;
}

插件源碼地址

GitHub: amibug/fly(支持自定義軌跡函數、回調擴展)


只需 20 行核心代碼,即可賦予電商頁面專業級的交互質感。建議在生產環境中加入「購物車數量彈跳」、「商品列表同步更新」等後續反饋,形成完整閉環。

copyright © 萬盛學電腦網 all rights reserved