CSS Transition Doesn't Start or Callback Isn't Called: Analysis
Your issue stems from a quirk in CSS transitions and the browser's rendering process. Initially, you inline HTML with CSS position values, setting a transition on the left and top properties. Upon adding new location values, you expected a transition, but it skipped without triggering a callback.
Intriguingly, adding a 1ms setTimeout to wrap the style change initiated the transition. However, sometimes the callback remained unfired. This behavior can be attributed to the browser's timing.
Explanation:
When the new style is set, the browser has yet to apply the inline style to the computed style. The element's computed style remains unset for left and top properties, defaulting to 0px. Any transition applied later simply matches the set values, leaving no transition to occur.
To resolve this, a reflow must be forced to update the styles. This can be done using the offsetHeight getter or other similar methods that trigger reflows.
Example Using offsetHeight:
<code class="javascript">let tablehtml = ` <div id="spanky" style="position: absolute; left: 10px; top: 10px; background-color:blue; width:20px; height:20px; transition: left 1000ms linear 0s, top 1000ms linear 0s;"> </div>`; document.body.innerHTML += tablehtml; let animdiv = document.getElementById('spanky'); animdiv.addEventListener("transitionend", function(event) { animdiv.style.backgroundColor='red'; }, false); // force a reflow animdiv.offsetTop; // now animdiv will have all the inline styles set // it will even have a proper display animdiv.style.backgroundColor='green'; Object.assign(animdiv.style, { left: "100px", top: "100px" });</code>
The above is the detailed content of Why Does My CSS Transition Skip and the Callback Fail to Fire?. For more information, please follow other related articles on the PHP Chinese website!