//封装添加任意多个属性的函数
//fn这个参数是为这个函数添加的回调函数
function changeAll(ele,json,fn){
//每次都清除一次定时器
clearInterval(ele.timed);
//设置定时器
ele.timed=setInterval(function() {
var flag=true;
//遍历json中的数据
//attr为json中的属性名,json[attr]为json中的属性值
for(var attr in json) {
//获取当前属性值
var now = parseInt(getStyle(ele, attr));
//设置每次改变的值
var step = (json[attr] - now) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
now += step;
//设置每次改变之后的样式
ele.style[attr] = now + 'px';
if (now !=json[attr]) {
flag=false;
}
}
if(flag){
//当所有的属性值都达到了自己设置的目标的时候,清除定时器
clearInterval(ele.timed);
//在上面的条件达到的时候,执行回调函数
if(fn){
fn();
}
}
},20);
}
案例:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 100px;
background-color: green;
position: absolute;
left: 0;
top: 20px;
}
</style>
</head>
<body>
<input type="button" value="改变div样式" id="btn" />
<div id="dv"></div>
<script src="js/common.js"></script>
<script src="js/getStyle.js"></script>
<script src="js/changespeadAll.js"></script>
<script>
var json={
'left':150,
'top':150,
'width':300,
'height':200
};
var json2={
'left':300,
'top':300,
'width':200,
'height':100
};
var json3={
'left':50,
'top':50,
'width':50,
'height':30
};
//获取div
var dv = my$('dv');
//设置按钮点击事件
my$('btn').onclick=function(){
changeAll(dv,json,function(){
changeAll(dv,json2,function(){
changeAll(dv,json3);
});
});
};
/*//封装添加任意多个属性的函数
function changeAll(ele,json){
//每次都清除一次定时器
clearInterval(ele.timed);
//设置定时器
ele.timed=setInterval(function() {
var flag=true;
//遍历json中的数据
//attr为json中的属性名,json[attr]为json中的属性值
for(var attr in json) {
//获取当前属性值
var now = parseInt(getStyle(ele, attr));
//设置每次改变的值
var step = (json[attr] - now) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
now += step;
//设置每次改变之后的样式
ele.style[attr] = now + 'px';
if (now !=json[attr]) {
flag=false;
}
}
if(flag){
clearInterval(ele.timed);
}
},20);
}*/
</script>
</body>
</html>
实现div的三次过渡动画