Home > Web Front-end > JS Tutorial > body text

Why Doesn\'t My CSS Transition Work With Inline Styles and How Do I Fix It?

Linda Hamilton
Release: 2024-10-29 01:28:02
Original
817 people have browsed it

 Why Doesn't My CSS Transition Work With Inline Styles and How Do I Fix It?

CSS Transition Doesn't Start or Callback Isn't Called

Problem:

In a JavaScript-based game project, attempts to replace jQuery animations with CSS transitions for projectile movements proved unsuccessful. The transitions skipped or didn't trigger the callback, even with the application of a setTimeout delay.

Explanation:

This behavior occurs because the browser hasn't applied inline CSS styles before it applies transition properties. When the new style is set, the element's computed style still has default values for display, left, and top positions.

Since left and top values remain at 0px (their default values), the transition has nothing to do as the values match those set in the new style. To rectify this, a browser reflow must be forced to update the styles before applying the transition.

Solution:

To force a browser reflow, utilize the Element.offsetHeight getter. For example:

<code class="js">// Assume animdiv is the element you want the transition to work on
animdiv.offsetTop;
// Now animdiv has all inline styles set

Object.assign(animdiv.style, {
  left: "100px",
  top: "100px"
});</code>
Copy after login

This step ensures the element's computed style is up-to-date, and the transition will be applied as expected.

The above is the detailed content of Why Doesn\'t My CSS Transition Work With Inline Styles and How Do I Fix It?. 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