添加购物车弧形动画
问题描述:购物车动画,就是选择的时候一个动画元素从选择处以抛物线调入左下角的购物车图标,进入后购物车有一个摇晃效果。(如下图)
-------------(×_×) 一个小小的动画,需求也是定制的,不高新到网上找插件。代码也不多。找的插件还要改东西,又引入更多代码。于是决定自己写。
解题思路:
相信大家也不愿意看大堆的代码,写下关键点吧。
1.准备:在选择的地方隐藏一个动画元素(使用fixed定位:因为动画应该是相对于屏幕的,而右边的列表长度大于屏幕,不能使用相对于文档的定位)。
2.过程:(1).选择的时候,先显示这个动画元素。然后根据抛物线路径parabola,每隔一个时间间隔,设置一下动画元素的left,bottom值。
(2).当到达购物车后隐藏动画元素,触发购物车摇晃动画。
3.详解:
(1).看一下抛物线函数:
function parabola(x,y,x1) {
//顶点为原点的抛物线,根据已知一个非原点A(x,y)和B(x1,y1)的x1值求B的y1值,返回y1。
return x1*x1*y/(x*x);
}
(2).路径绘制关键代码用颜色表示出了。
$(".order_wrap").on("click",".checkbox1 input",function () {
var $this=$(this);
var li=$this.parents("li");
var _class=li.attr("id");
var span=$(".type_li."+_class).find(".num");
var food=$this.parents(".food");
var dot= food.find(".dot");
var num=(span.text()==NaN||span.text()==''||span.text()==undefined)?0:parseInt(span.text());
var html="";
if($this.is(":checked")){
//类型上个数修改
num+=1;
span.text(num);
//加入购物车动画
$(".cart_i").removeClass("animate");
dot.css({
"display":"inline-block"
});
var x=dot[0].getBoundingClientRect().left;
var y=dot[0].getBoundingClientRect().top-$(".cont").scrollTop();
for(var i=0;i<=x/10;i++){
dot.animate({
bottom:bottom.top-(parseInt(parabola(x-bottom.left,bottom.top-y,i*10)))-y+"px",
left:x-i*10-bottom.left+"px"
},10,function () {
if(dot.offset().left<10){
dot.css({
"display":"none"
});
$(".cart_i").addClass("animate");
}
});
}
//购物车添加html元素
html='<div class="oh food '+food.attr("id")+'" data-id='+food.attr("id")+'> <label class="checkbox1 y"> <input type="checkbox" checked> <i class="checkbox1_i"></i> </label> <div class="name omit">'+food.find(".name").text()+'</div> </div>';
$(".cart .foods").append($(html));
}else{
num-=1;
span.text(num);
//擦除购物车动画痕迹
dot.css({"bottom":"auto","left":"auto"});
food.find(".dot").removeClass("on");
//购物车html元素删除
$(".cart").find("."+food.attr("id")).remove();
}
//类型上面数量的显示和隐藏
if(num>0){
span.addClass("show");
}else{
span.removeClass("show");
}
});
(3).购物车动画:css3动画属性。
@keyframes cart {
0%{
transform: scale(1,1) rotate(0deg);
-webkit-transform: scale(1,1) rotate(0deg);
opacity: 1;
}
30%{
transform: scale(1,1) rotate(-30deg);
-webkit-transform: scale(1,1) rotate(-30deg);
}
50%{
transform: scale(1.2,1.2) rotate(0deg);
-webkit-transform: scale(1.2,1.2) rotate(0deg);
}
70%{
transform: scale(1,1) rotate(10deg);
-webkit-transform: scale(1,1) rotate(10deg);
}
100%{
transform: scale(1,1) rotate(0deg);
-webkit-transform: scale(1,1) rotate(0deg);
opacity: 1;
}
}
.cart_i.animate{
animation: cart 0.5s;
animation-timing-function: linear;
-webkit-animation: cart 0.5s;
-webkit-animation-timing-function: linear;
}