Home > Web Front-end > JS Tutorial > Why Does My CSS Transition Skip and the Callback Fail to Fire?

Why Does My CSS Transition Skip and the Callback Fail to Fire?

Mary-Kate Olsen
Release: 2024-10-31 08:48:29
Original
854 people have browsed it

Why Does My CSS Transition Skip and the Callback Fail to Fire?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template