系列文章导航
JavaScript动画1-速度动画
JavaScript动画2-缓冲运动
JavaScript动画3-多物体运动
JavaScript动画4-任意属性值
JavaScript动画5-链式运动
JavaScript动画6-同时运动
所有源代码
链式运动
如果我们想让一个元素变长之后,再变高,再改变透明度,那该怎么办?
我们当然可以不断地调用同一个动画函数,就像这样:
change(div, 'width', 400);
change(div, 'height', 400);
change(div, 'opacity', 30);
但这样显然太麻烦了,如果能在同一个函数里执行所有的动画就好了。我们可以在change函数中再加一个参数,这个参数是一个函数的引用:
//链式运动
(function () {
var div7 = document.getElementById("div7");
div7.onmouseover = function () {
var _this = this;
change(_this, 'width', 400, function () {
change(_this, 'height', 400, function () {
change(_this, 'opacity', 30, function () {
change(_this, 'opacity', 100, function () {
change(_this, 'height', 200, function () {
change(_this, 'width', 200);
});
});
});
});
});
};
function change(obj, attr, targetValue, fn) {
if (obj.timer) {
clearInterval(obj.timer);
}
obj.timer = setInterval(function () {
var currentValue = 0;
if (attr == 'opacity') {
currentValue = Math.round((parseFloat(getStyle(obj, attr)) * 100));
} else {
currentValue = parseInt(getStyle(obj, attr));
}
var speed = (targetValue - currentValue) / 10; //缓冲运动
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (currentValue == targetValue) {
clearInterval(obj.timer);
if (fn) {
fn();
}
} else {
if (attr == 'opacity') {
obj.style.opacity = (currentValue + speed) / 100;
} else {
obj.style[attr] = currentValue + speed + 'px';
}
}
}, 20);
}
})();
最终效果:
JS动画演示9