JS-Native Animation Packaging

Keywords: JSON Attribute

JS-Native Animation Packaging

Realization effect


In offset section, uniform animation and slow animation are realized, but only one attribute can be set at a time, and the animation can not be executed sequentially, so we need to solve the problem:

  • Pass an array of style information to the function, and all attributes are synchronized when animation is executed.
  • If more than one animation needs to be executed in sequence, the next statement will be passed to the previous statement and executed in sequence.
  • If delay is required, the statement passed from the latter to the former can be added with a timer.

Code

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<style>
 *{
  margin:0;
  padding:0;
  font-family:"Microsoft YaHei";
 }
 #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 assigns t for easy operation
		var json={	//Animation 1
			"top":25,
			"left":100,
			"width":100,
			"height":100,
			"line-height":100,
			"font-size":30
		};
		var json2={	//Animation 2
			"top":50,
			"left":190,
			"width":50,
			"height":50,
			"line-height":50,
			"font-size":14
		};
		animate(t,json,function(){
			setTimeout(function(){	//Delay 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; //Get the source value and assign 0 if not
				var dir=current<json[key] ? 1 : -1; //Determine direction
				ele.style[key]=current+dir*Math.ceil(Math.abs(current-json[key])/10)+"px";
				if(json[key]!=current){ //All parameters are in place before stopping
					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>

The above code can only achieve the left,width,font-size and other integer numerical style animation, opacity and other decimal style can not be achieved, color, backgroundand other complex styles can not be achieved, but can be specifically parsed for a style.

Posted by peaforabrain on Tue, 08 Oct 2019 00:29:16 -0700