最近項目需要一個添加購物車動畫,然後自己研究了一下
先上效果圖
商品靜靜躺在那裡
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISNzYTMxYjMzITOwkDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
點選購物車,開始播放動畫
最終,商品圖檔落入購物車
商品圖檔落入購物車後,有一個回調函數可以在動畫播放完畢執行真正的加入購物車操作,比如在購物車加上一個數字什麼的
以下是全部代碼
<!doctype html>
<html>
<head>
<title>購物車動畫</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="jquery.js"></script>
<script src="jquery.easing.1.3.min.js"></script>
</head>
<body>
<img class="googsimg" src="1.jpg" />
<br />
<div><button>加入購物車</button></div>
<div class="nav">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<style type="text/css">
body { margin: 0; }
.googsimg { width: 200px; height: auto; }
.nav { width: 100%; height: 50px; position: fixed; bottom: 0; }
ul { margin: 0; padding: 0; }
li { margin: 0; padding: 0; list-style: none; float: left; width: 25%; text-align: center; line-height: 50px; height: 50px; border: solid 1px black; box-sizing: border-box; }
</style>
<script>
function AddToCart(fromEl, toEl, callback)
{
var fromX = fromEl.offset().left
var fromY = fromEl.offset().top - $(document).scrollTop()
var toX = toEl.offset().left
var toY = toEl.offset().top - $(document).scrollTop()
var img = document.createElement('img')
img.src = fromEl.attr('src')
img.style.width = fromEl.width() + 'px'
img.style.height = fromEl.height() + 'px'
img.style.position = 'fixed'
img.style.zIndex = '1000'
img.style.left = fromX + 'px'
img.style.top = fromY + 'px'
document.getElementsByTagName('body')[0].appendChild(img)
var fakeEl = $(img)
fakeEl.animate({
left: toX
}, 2000, null, function ()
{
fakeEl.animate({
width: fromEl.width() * 0.2,
height: fromEl.height() * 0.2,
top: toY
}, 2000, null, function ()
{
fakeEl.remove()
if (callback)
{
callback()
}
})
})
}
$('button').click(function ()
{
AddToCart($('.googsimg'), $('li').eq(2), function ()
{
console.log('一件商品已經加入購物車')
})
})
</script>
</body>
</html>