電商項目中,「加入購物車」的拋物線飛入動畫能顯著提升操作反饋感與轉化率。本文基於 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]-->
<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>
$(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();
}
});
});
});
event.pageX/Y 獲取點擊位置,視覺上從按鈕處「飛出」;offset() + 微調偏移,確保落入圖標中心;<img>,設置 position: absolute; z-index: 9999; pointer-events: none;(插件內部處理);this.destroy() 移除 DOM、清理定時器,防止內存洩漏;requestAnimationFrame,需引入 polyfill。.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 行核心代碼,即可賦予電商頁面專業級的交互質感。建議在生產環境中加入「購物車數量彈跳」、「商品列表同步更新」等後續反饋,形成完整閉環。