简体   繁体   中英

restart/reset and replay a transition css?

I need to replay a css transition using javascript. When I reset css style of my div and apply the new transition, nothing happens...

I think both code are executed in the same execution frame and by optimisation, it doesn't change anything...

Example : https://jsfiddle.net/f0s8a8jp/2/

test.css({transition: 'none', height: '0px'});
test.css({transition: 'height 1s linear', height: '100px'});

The only solution I found for the moment (not realy clean for me), is to use setTimeout beetween the properties reset and the application of new transition : https://jsfiddle.net/f0s8a8jp/3/

Better idea is welcome?!

The transition will apply on the computed dimension of the element. Setting the CSS property does not compute it. So, setting forth and back the property is like letting it unchanged. It's computed when the browser need to reflow the element.

setTimeout will eventually let the time to the browser to compute a reflow in the meanwhile. You could use requestAnimationFrame to achieve the same without flickering.

Another hack consists in forcing the browser to reflow right after altering the CSS properties, using test[0].offsetWidth; for instance. The transition is then performed correctly: https://jsfiddle.net/f0s8a8jp/9/

A more in-depth discussion about reflow (and repaint) can be found here: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/

Try this:

https://jsfiddle.net/f0s8a8jp/4/

I made it work on click , so you need to click on it to see the result.

The only thing I really changed was the order of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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