DIV CSS 佈局教程網

jQuery實現加入購物車飛入動畫效果
編輯:JQuery特效代碼     

本文將實現一個常見的電商交互:當用戶點擊「加入購物車」時,商品圖片會縮成一個小球,沿拋物線飛向頁面右側的購物車並提示操作成功。整個軌跡動畫由 jquery.fly 插件完成,我們只需定義起點與終點。

引入依賴

首先在頁面中載入 jQuery 庫與 fly 插件:

<script src="jquery.js"></script>
<script src="jquery.fly.min.js"></script>

HTML 結構

用四個並排的商品 box 布置商品信息,每個 box 包含圖片、價格、名稱與加入購物車按鈕:

<div class="box">
  <img src="images/lg.jpg" width="180" height="180">
  <h4>¥<span>3499.00</span></h4>
  <p>LG 49LF5400-CA 49寸IPS硬屏富貴招財銅錢設計</p>
  <a href="#" class="button orange addcar">加入購物車</a>
</div>

頁面右側放置購物車與提示信息:

<div class="m-sidebar">
  <div class="cart">
    <i id="end"></i>
    <span>購物車</span>
  </div>
</div>
<div id="msg">已成功加入購物車!</div>

CSS 樣式

先用 CSS 排列並美化商品,再設置右側懸浮購物車的樣式:

.box{float:left; width:198px; height:320px; margin-left:5px; border:1px solid #e0e0e0; text-align:center}
.box p{line-height:20px; padding:4px 4px 10px 4px; text-align:left}
.box:hover{border:1px solid #f90}
.box h4{line-height:32px; font-size:14px; color:#f30;font-weight:500}
.box h4 span{font-size:20px}
.u-flyer{display: block;width: 50px;height: 50px;border-radius: 50px;position: fixed;z-index: 9999;}
.m-sidebar{position: fixed;top: 0;right: 0;background: #000;z-index: 2000;width: 35px;height: 100%;font-size: 12px;color: #fff;}
.cart{color: #fff;text-align:center;line-height: 20px;padding: 200px 0 0 0px;}
.cart span{display:block;width:20px;margin:0 auto;}
.cart i{width:35px;height:35px;display:block; background:url(car.png) no-repeat;}
#msg{position:fixed; top:300px; right:35px; z-index:10000; width:1px; height:52px; line-height:52px; font-size:20px; text-align:center; color:#fff; background:#360; display:none}

jQuery 邏輯

點擊按鈕時,獲取當前商品圖片並生成飛行動畫元素,調用 fly 插件,指定起點為鼠標位置、終點為購物車位置,動畫結束後給出提示並移除臨時元素:

<script>
$(function() {
  var offset = $("#end").offset();
  $(".addcar").click(function(event){
    var addcar = $(this);
    var img = addcar.parent().find('img').attr('src');
    var flyer = $('<img class="u-flyer" src="'+img+'">');
    flyer.fly({
      start: {
        left: event.pageX, //開始位置(必填)
        top: event.pageY   //開始位置(必填)
      },
      end: {
        left: offset.left+10, //結束位置(必填)
        top: offset.top+10,   //結束位置(必填)
        width: 0,             //結束時寬度
        height: 0             //結束時高度
      },
      onEnd: function(){      //結束回調
        $("#msg").show().animate({width: '250px'}, 200).fadeOut(1000);
        addcar.css("cursor","default").removeClass('orange').unbind('click');
        this.destory();       //移除dom
      }
    });
  });
});
</script>

復制上述代碼保存運行即可看到效果。Fly 插件的項目地址為 https://github.com/amibug/fly ,值得一提的是,IE10 以下還需額外引入 requestAnimationFrame.js 以兼容動畫。以上就是本文的全部內容,希望大家能夠喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved