JS-原生动画封装

JS-原生动画封装

实现效果


在offset小节,实现了匀速动画和缓动动画,但每次只能设置一个属性,且动画不能先后有序执行,所以要解决:

  • 给函数传递一个包含样式信息的数组,执行动画时所有属性同步进行
  • 若有多个动画需依次执行,后面的语句传给前面的语句,依次执行
  • 若需要延时,后者传给前者的语句可以加上计时器

代码

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<style>
 *{
  margin:0;
  padding:0;
  font-family:"微软雅黑";
 }
 #box{
  width:50px;
  height:50px;
  color:#fff;
  text-align:center;
  font-size:14px;
  line-height:50px;
  position:relative;
  background:#08f;
  top:50px;
  left:10px;
  border-radius:100%;
 }
</style>
</head>
<body>
<div id="box">box</div>
<script>
	var box=document.getElementById("box");
	box.onclick=function(){
		var t=this;	//this赋给t方便操作
		var json={	//动画1
			"top":25,
			"left":100,
			"width":100,
			"height":100,
			"line-height":100,
			"font-size":30
		};
		var json2={	//动画2
			"top":50,
			"left":190,
			"width":50,
			"height":50,
			"line-height":50,
			"font-size":14
		};
		animate(t,json,function(){
			setTimeout(function(){	//延时1s
				animate(t,json2);
			},1000);
		});
	};
	function animate(ele,json,fn){
		clearInterval(ele.timer);
		ele.timer=setInterval(function(){
			var flag=true;
			for(var key in json){
				var current=parseInt(getStyle(ele,key)) || 0; //获取源值,若无则赋0
				var dir=current<json[key] ? 1 : -1; //确定方向
				ele.style[key]=current+dir*Math.ceil(Math.abs(current-json[key])/10)+"px";
				if(json[key]!=current){ //所有参数都到位再停止
					flag=false;
				}
			}
			if(flag){
				clearInterval(ele.timer);
				if(fn){
					fn();
				}
			}
		},24);
	}
	function getStyle(ele, attr) {
		if (window.getComputedStyle) {
			return window.getComputedStyle(ele, null)[attr];
		}
		return ele.currentStyle[attr];
	}
</script>
</body>
</html>

以上代码只能实现left,width,font-size等整数数值类样式的动画,opacity等小数位样式不能实现,color,background等复杂样式不能实现,但可以针对某个样式进行专门的解析

猜你喜欢

转载自www.cnblogs.com/yangjiale/p/11330529.html