原生js制作动画效果

理论基础:需要获取元素的任意css属性值
getComputedStyle(element,null),支持谷歌,火狐
element.currentStyle,支持ie8

//获取任意css属性值(兼容性代码)
function getStyleAttr(element,attr){
	return window.getComputedStyle?window.getComputedStyle(element,null)[attr]:element.currentStyle[attr];
}

获取到了任意的属性值,接下来开始写原生js动画的封装函数
函数的参数element(元素对象),json(json对象),fn(自定义的回调函数)

		function autoAnimate(element,json,fn) {
			//清除定时器
			clearInterval(element.tmId);
			element.tmId= setInterval(function(){
				for(var attr in json){
					var flag=true;
					//获取操作的css属性(根据上述的兼容方法获取)
					var current=parseInt(getStyleAttr(element,attr));
					//步数
					var step=10;
					//步长(每一步运动的像素)
					speed=(json[attr]-current)/step;
					//判断左右移动
					speed= json[attr]>current?Math.ceil(speed):Math.floor(speed);
					//每一步运动的位置
					current+=speed;
					//开始运动
					element.style[attr]=current+"px";
					if(current!=json[attr]){
						console.log(current,json[attr]);
						flag=false;
					}
					// console.log("步长"+speed,"当前位置"+current,"目标"+json[attr]);
				}
				if(flag){
					//满足条件关闭定时器
					clearInterval(element.tmId);
					if(fn)fn();//执行回调函数
				}
			},200);
		}

最后附上js动画完整的封装过程?

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	#dv{
		width: 300px;
		height: 300px;
		background-color: orange;
		position: absolute;
	}
</style>
</head>
<body>
	<button id="btn">动画</button>
	<div id="dv">动画效果</div>

	<script src="common.js"></script>
	<script>
		$query("#btn").onclick=function(){
			autoAnimate($query("#dv"),{"width":100,"height":100,"fontSize":10},function(){
				console.log("I'm ok");
			});
		}
		//获取任意css属性值
		function getStyleAttr(element,attr){
			return window.getComputedStyle?window.getComputedStyle(element,null)[attr]:element.currentStyle[attr];
		}
		//封装的动画函数
		function autoAnimate(element,json,fn) {
			//清除定时器
			clearInterval(element.tmId);
			element.tmId= setInterval(function(){
				for(var attr in json){
					var flag=true;
					//获取操作的css属性
					var current=parseInt(getStyleAttr(element,attr));
					//步数
					var step=10;
					//步长(每一步运动的像素)
					speed=(json[attr]-current)/step;
					//判断左右移动
					speed= json[attr]>current?Math.ceil(speed):Math.floor(speed);
					//每一步运动的位置
					current+=speed;
					//开始运动
					element.style[attr]=current+"px";
					if(current!=json[attr]){
						console.log(current,json[attr]);
						flag=false;
					}
					// console.log("步长"+speed,"当前位置"+current,"目标"+json[attr]);
				}
				console.log("--------------------");
				if(flag){
					clearInterval(element.tmId);
					if(fn)fn();
				}
			},200);
		}
	</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值