Why does omitting 0ms sleep break my css transitions?
P粉6595169062024-04-06 16:29:50
0
2
1097
I'm trying to implement a FLIP animation to see if I understand it correctly.
In this codepen (please forgive the bad code, I'm just messing around), if I comment out the sleep, the smooth transition no longer works. The div changes position suddenly. This is strange because the sleep time is 0ms.
You are using a normal JavaScript solution to this problem, but React uses a virtual DOM and expects DOM elements to be re-rendered when state changes. Therefore, I recommend leveraging React state to update the XY position of elements in the virtual DOM, but still using CSS.
During sleep, the browser may have time to recalculate the CSSOM box (also known as "execution reflow"). Without it, your transform rules won't actually apply.
In fact, the browser will wait until it's really needed to apply your changes and update the entire page box model, because doing so can be very expensive.
When you do something like
All CSSOMs will see is the latest status, "green". The other two were discarded.
So in your code, when you don't let the event loop actually loop, you will never see the transStr value either.
However, relying on 0ms setTimeout is a problem call, there is nothing to ensure that the style is recalculated at that time. Instead, it's better to force a recalculation manually. Some DOM methods/properties do this synchronously. But keep in mind that reflow can be a very expensive operation, so be sure to use it occasionally, and if there are multiple places in your code that require this operation, be sure to connect them all so that a single reflow can be performed. p>