An HTML element's position is updated using CSS transitions. However, the transition fails to trigger or the callback function is not invoked despite adding a transition transitionend event listener. This issue can be solved by wrapping the change with a setTimeout(1ms).
The reason behind this behavior lies in the browser's rendering process. Before the browser can apply the CSS transition, it must first apply the inline styles to the element. If the element is not yet in the DOM, its computed style display is set to "".
When the new style is set, the browser has not yet applied the inline style. Therefore, the element's computed style remains as "", with its left and top values still at 0px.
Consequently, when the transition property is applied before the next frame paint, the left and top values are already the desired ones, resulting in no transition to perform and no triggering of the transitionend event.
To resolve this issue, a reflow can be forced using the Element.offsetHeight getter or other DOM methods that require up-to-date styles. This forces the browser to update the styles before applying the transition, ensuring a smooth implementation.
The following code demonstrates the issue and its workaround:
document.body.innerHTML = tablehtml;
var animdiv = document.getElementById('spanky');
animdiv.addEventListener("transitionend", function(event) {
animdiv.style.backgroundColor = 'red';
}, false);
// force a reflow
animdiv.offsetTop;
animdiv.style.backgroundColor = 'green';
Object.assign(animdiv.style, {
left: "100px",
top: "100px"
});
In this example, the animdiv element's offsetTop getter is used to force a reflow before its position is updated. This ensures that the CSS transition properly triggers and the callback function is invoked.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3