当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript reversed animation not working properly

问题描述:

What I want to achieve: Start an animation and then immediately reverse it when needed. The reverse would work from anywhere within the loop. I'm animating individual characters of a text within a div (each letter within their own span (c)).

My problem: It seems I underestimated my concept a little bit. I can't make the reverse work as I would like it to. It does reverse but only under a certain unwanted condition: It has to reverse before the end of the increment loop (index 11). Set the timeout of the reverse function call to 2000 and then try it with 3000. Reverse works with the first but not the latter.

What I tried: I console.logged many things to be sure that everything functions correctly. Unfortunately I get an error:

Uncaught TypeError: Cannot read property 'style' of undefined. It fires as soon as my reverse should initiate. This of course did not make sense to me since my dom element should be defined, be it incrementing or decrementing the index "i", the definition should be retained. Other than that I have been trying various structural changes in the hope for an improvement.


Jsfiddle Demo: http://jsfiddle.net/9cm3Lwem/6/


Find the following code:

setTimeout(function() {

text.reverse();

}, 3000)

Try it with 2000 (reverse during animation) and 3000 (lets the animation finish before reversal) and observe the changes.

My question: Why is my reverse not working correctly and what can I do in order to solve this in an elegant manner?

网友答案:

I looked at your code in the jsFiddle. Your "reverse" function changes the "state" variable, but it doesn't cause the "play" function to run again. Therefore, if you run your code with reverse being invoked after 3000 ms as you have shown, only the state variable is changed. You need to make it so that the play function can be invoked again if it isn't already on the timer.

分享给朋友:
您可能感兴趣的文章:
随机阅读: