这是一款效果非常炫酷的基于jQueryUI的商品添加到购物车动画特效。该购物车动画在用户点击添加到购物车按钮之后,该商品的缩略图会被缩小,并移动到购物车小图标中,制作出将商品放入购物车内的效果。
制作方法
HTML结构
该购物车动画特效的HTML结构采用嵌套<div>的HTML结构。每一个div.item是一个商品。span.car是购物车小图标。
<div class="wrapper">
<h1 class="title">Phone Stock</h1>
<span class="car"><i class="shopping-cart"></i></span>
<div class="clear"></div>
<!-- items -->
<div class="items">
<!-- single item -->
<div class="item">
<img src="img/droid-x.jpg" alt="item" />
<h2>droid-x</h2>
<p>Price: <em>$255</em>
</p>
<button class="add-to-cart" type="button">Add to cart</button>
</div>
<!--/ single item -->
...
</div>
<!--/ items -->
</div>
CSS样式
这个效果的CSS样式非常简单,它使用元素浮动模式将各个商品排列为网格布局。
.wrapper {
width: 705px;
margin: 20px auto;
padding: 20px;
}
.items {
display: block;
margin: 20px 0;
}
.item {
background-color: #fff;
float: left;
margin: 0 10px 10px 0;
width: 205px;
padding: 10px;
height: 290px;
}
.item img {
display: block;
margin: auto;
}
h2 {
font-size: 16px;
display: block;
border-bottom: 1px solid #ccc;
margin: 0 0 10px 0;
padding: 0 0 5px 0;
}
button {
border: 1px solid #722A1B;
padding: 4px 14px;
background-color: #fff;
color: #722A1B;
text-transform: uppercase;
float: right;
margin: 5px 0;
font-weight: bold;
cursor: pointer;
}
span.car {
float: right;
}
.shopping-cart {
display: inline-block;
background: url('../img/_cart.png') no-repeat 0 0;
width: 24px;
height: 24px;
margin: 0 10px 0 0;
}
JAVASCRIPT
在jQuery代码中,为每一个.add-to-cart按钮绑定了鼠标点击事件。然后通过按钮来查找该按钮对应的水平的缩略图。如果缩略图存在,就通过clone()方法将它复制一份。最后通过animate()方法来将缩略图副本进行移动操作。在添加商品之后购物车的抖动动画通过设置一个定时器来完成。
$('.add-to-cart').on('click', function () {
var cart = $('.shopping-cart');
var imgtodrag = $(this).parent('.item').find('img').eq(0);
if (imgtodrag) {
var imgclone = imgtodrag.clone().offset({
top: imgtodrag.offset().top,
left: imgtodrag.offset().left
}).css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
}).appendTo($('body')).animate({
'top': cart.offset().top + 10,
'left': cart.offset().left + 10,
'width': 75,
'height': 75
}, 1000, 'easeInOutExpo');
setTimeout(function () {
cart.effect('shake', { times: 2 }, 200);
}, 1500);
imgclone.animate({
'width': 0,
'height': 0
}, function () {
$(this).detach();
});
}
});