封装运动框架单个属性

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>封装运动框架的单个属性</title>
<style>
div{
width: 100px;
height: 100px;
font-weight:bold;">pink;
position: absolute;
left: 10px;
top: 50px;

}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="demo"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var demo = document.getElementById("demo");
btn200.onclick = function(){
animate(demo,"width",400);
}
btn400.onclick = function(){
animate(demo,"left",100);
}
function animate(obj,attr,target){
clearInterval(obj.timer);
obj.timer = setInterval(function() {
//先算出步长 盒子的动画原理 盒子本身的样式+步长
//我们怎么知道当前的样式
//得到当前样式后,用(target - current )/10 计算出步长
//得到当前样式 parseInt目的是为了去掉PX
var current = parseInt(getStyle(obj,attr));
var step = (target - current) / 10;
step = step > 0? Math.ceil(step):Math.floor(step); //取整函数

//开始做动画
obj.style[attr] = current + step + "px";
if(target == current){
clearInterval(obj.timer);
}

},30)
}


//封装返回当前样式函数
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr];
}
}
</script>
posted @ 2017-08-01 22:44  寻觅聪  阅读(111)  评论(0编辑  收藏  举报