我正在尝试先div
水平然后再垂直设置动画。但是使用的问题requestAnimationFrame
是它同时执行两个动画,使div
行程成对角线。
这是小提琴链接:https : //jsfiddle.net/akonchady/z4qmkuyc/22/
我究竟做错了什么?
注意:如果我为第二次调用指定了超时,则它可以按预期工作:
animate('abc', 'marginLeft', 250, 1000);
setTimeout(function() {
animate('abc', 'marginTop', 250, 1000);
}, 3000);
但是我想避免超时。我怎样才能做到这一点requestAnimationFrame
?
functions
JavaScript中的大多数代码都是同步的(将顺序执行)。但是对于asynchronous
函数(不会等待较早的函数完成),请使用callbacks
来控制执行流程。
要function
在第一个动画完成后调用send ,请使用callback
function animate(id, styleAttr, finalValue, duration, callback) {
var ele = document.getElementById('abc'),
startTime = +new Date, //Not sure how readable this is ?
delta = null,
req = null;
(function timeout() {
elapsedTime = +new Date - startTime;
if (elapsedTime >= duration) {
cancelAnimationFrame(req);
ele.style[styleAttr] = finalValue + 'px';
if (typeof callback !== 'undefined') {
callback();
}
return;
} else {
delta = finalValue / duration;
ele.style[styleAttr] = delta * elapsedTime + 'px';
}
req = requestAnimationFrame(timeout);
})();
}
animate('abc', 'marginLeft', 250, 1000, function() {
animate('abc', 'marginTop', 250, 1000);
});
#abc {
width: 100px;
height: 100px;
background-color: red;
}
<div id='abc'>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句