/**
* 例子:getStyle(my$("box"),"height")
* 获取一个元素的任意样式属性 返回一个字符串类型
* @param {Object} ele 元素
* @param {Object} attr 样式属性
*/
function getStyle(ele, attr) {
return window.getComputedStyle ? window.getComputedStyle(ele, null)[attr] : ele.currentStyle[attr];
}
11
/**
* 多属性变化
* @param {Object} ele 要变化的元素
* @param {Object} json 改变后的样式对象
* @param {Object} fn 回调函数
*/
function animate(ele, json, fn) {
//清理定时器
clearInterval(ele.timeId);
//定时器
ele.timeId = setInterval(function() {
var flag = true; //定义一个锁 假设全部到达目标
for(var attr in json) {
//遍历每个元素让每个元素到达对应目标
if(attr == "opacity") { //透明度
var current = getStyle(ele, attr) * 100;
var target = json[attr] * 100;
var step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current += step;
ele.style[attr] = current / 100;
} else if(attr == "zIndex") { //层次
ele.style[attr] = json[attr];
console.log(ele.style[attr]);
} else { //普通属性
//获取当前值
var current = parseInt(getStyle(ele, attr));
//目标值
var target = json[attr];
//变化
var step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
//移动后的值
current += step;
ele.style[attr] = current + "px";
}
if(current != target) {
flag = false;
}
}
if(flag) {
clearInterval(ele.timeId)
if(fn) {
fn();
}
}
console.log("目標:" + target + "---當前:" + current);
}, 20)
}
调用
my$("btn").onclick = function() {
var aabb = { "width": 400, "height": 200, "opacity": 0.2, "zIndex": 10, "left": 500 };
var bbaa = { "width": 100, "height": 300, "opacity": 0.6, "zIndex": 1000, "left": 0, "top": 0 };
animate(my$("box"), aabb, function() {
animate(my$("box"), bbaa);
})
}