<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="format-detection" content="telephone=yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<title>购物车动画实现</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #f8f8f9;
}
/*商品列表*/
.item {
border-radius: 8px;
background-color: white;
display: flex;
justify-content: space-between;
align-items: flex-end;
padding: 15px;
margin: 15px;
}
.item .img {
width: 60px;
height: 60px;
background-size: cover;
background-position: center center;
border-radius: 6px;
margin-right: 13px;
border: 1px solid #eee;
}
.item .label {
align-self: flex-start;
flex-grow: 1;
}
.item .buy {
background: #8B61AA;
border-radius: 4px;
height: 30px;
line-height: 30px;
padding: 0 10px;
font-size: 12px;
display: inline-block;
white-space: nowrap;
text-align: center;
color: white;
}
/*购物车*/
.cart-area {
position: fixed;
bottom: 0;
height: 60px;
width: 100%;
background-color: #80848f;
display: flex;
align-items: center;
}
.cart-area .cart {
background-color: white;
color: #495060;
height: 50px;
width: 50px;
margin: 10px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
}
</style>
</head>
<body>
<h3 style="margin: 15px">商品入车动画(jq版)</h3>
<!--商品列表-->
<div class="list">
<div class="item">
<div class="img" style="background-image: url(//oss.xiaosk.com/library/thumb/etms_nfo/2019/2019-05-23/170FCA3E747A4D9AA48DF54A7F6770BC/pic.jpg);"></div>
<div class="label">
<h4>商品</h4>
<br>
<p>这是一个好商品</p>
</div>
<div class="buy">购买</div>
</div>
</div>
<!--购物车-->
<div class="cart-area">
<div class="cart">车</div>
</div>
<script>
// 取购物车
const cart = $('.cart');
// 购买按钮绑定事件
$('.buy').on('click', function () {
// 1. 获取需要复制的图片对象
const initImg = $(this).siblings('.img').eq(0);
// 2. 获取对象的 属性值
const style = {
width: initImg.width(),
height: initImg.height(),
backgroundImage: initImg.css('backgroundImage'),
backgroundSize: initImg.css('backgroundSize'),
backgroundPosition: initImg.css('backgroundPosition'),
borderRadius: initImg.css('borderRadius'),
position: 'absolute',
top: initImg.offset().top,
left: initImg.offset().left
};
// 3. 创建新的图片
const newImg = initImg.clone().css(style);
// 4. 把复制的图片添加到页面中
$('body').append(newImg);
// 5. 图片的入车动画
newImg.animate({ borderRadius: '50%', top: initImg.offset().top - initImg.height()/2, left: initImg.offset().left + initImg.width()/5 }, 300, 'swing');
newImg.animate({ width: 0, height: 0, top: cart.offset().top + cart.height()/2, left: (cart.offset().left + cart.width() / 2) }, 300, 'swing', function() {
newImg.remove();
});
})
</script>
</body>
</html>