缓动框架
在body中创建一个按钮
<button>运动到400</buttton>
<div></div>
设置样式
<style>
div{
position: absolute;
left:40px;
top:40px;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
程序运行起来的时候书写算法
window.onload = function () {
<!--分三步-->
<!--1.获取事件源-->
<!--获取标签-->
var button = document.getElementsByTagName("button")[0];
var div = document.getElementsByTagName("div")[0];
<!--2.绑定事件-->
button.onclick = function () {
<!--3,书写事件-->
var json1 = {"left":300,"top":200,"width":300,"height":200};
var json2 = {"left":40,"top":40,"width":100,"height":100};
<!--封装方法-->
<!--传事件源,json串,需要循环的方法-->
animate(div,json1,function(){
animate(div,json2,function(){
<!--可以取实现方法,也可以不去实现-->
});
});
}
function animate(ele,json,fn){
<!--首先清空定时器-->
clearInterval(ele.timer);
ele.timer = setInterval(function () {
// 开闭原则
var bool = true;
<!--获取步长-->
for(var k in json){
var leader = parseInt(getStyle(ele,k))||0
var step = (json[k] - leader)/10;
step = step>0 ? Math.ceil(step):Math.floor(step);
leader = leader + step;
<!--赋值-->
ele.style[k] = leader + "px";
if(json[k] != leader){
bool = false;
}
}
if (bool){
clearInterval(ele.timer);
if (fn){
fn();
}
}
},25);
//适配浏览器
function getStyle(ele,attr) {
if (window.getComputedStyle){
return window.getComputedStyle(ele,null)[attr];
}
return ele.currentStyle[attr];
}
}
}
运行之后的效果