理论基础:需要获取元素的任意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>