最近项目需要一个添加购物车动画,然后自己研究了一下
先上效果图
商品静静躺在那里
点击购物车,开始播放动画
最终,商品图片落入购物车
商品图片落入购物车后,有一个回调函数可以在动画播放完毕执行真正的加入购物车操作,比如在购物车加上一个数字什么的
以下是全部代码
<!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>