简体   繁体   English

使用requestAnimationFrame动画化div

[英]Animating a div with requestAnimationFrame

I am trying to animate a div horizontally first and then vertically. 我试图首先水平动画div ,然后垂直动画。 But the problem using requestAnimationFrame is that it is doing both animations at once, making the div travel diagonally. 但是使用requestAnimationFrame的问题在于它同时执行两个动画,使div对角移动。

Here is the fiddle link: https://jsfiddle.net/akonchady/z4qmkuyc/22/ 这是小提琴链接: https//jsfiddle.net/akonchady/z4qmkuyc/22/

What am I doing wrong? 我究竟做错了什么?

Note: It works as expected if I give a timeout for the second invocation as follows: 注意:如果我给第二次调用超时,它按预期工作,如下所示:

 animate('abc', 'marginLeft', 250, 1000); setTimeout(function() { animate('abc', 'marginTop', 250, 1000); }, 3000); 

However I want to avoid the timeout. 但是我想避免超时。 How can I achieve this just using requestAnimationFrame ? 如何使用requestAnimationFrame实现这一目标?

Most functions in JavaScript are synchronous(will execute sequentially). JavaScript中的大多数functions都是同步的(将按顺序执行)。 But with asynchronous functions(which will not wait for earlier function to finish), use callbacks to control the flow of the execution. 但是使用asynchronous函数(不会等待早期函数完成),使用callbacks来控制执行流程。

To invoke send function when first one is done with the animation, use callback 要在第一个完成动画时调用发送function ,请使用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> 

Fiddle Demo 小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM