Home > Web Front-end > CSS Tutorial > How Can I Pass JavaScript Variables to CSS Animations?

How Can I Pass JavaScript Variables to CSS Animations?

DDD
Release: 2024-12-08 01:06:12
Original
604 people have browsed it

How Can I Pass JavaScript Variables to CSS Animations?

Passing Variables to CSS Animations with JavaScript

When working with CSS animations, the ability to pass values as parameters from JavaScript can be incredibly useful. This allows for a dynamic and interactive experience.

Solution: CSS Variables

In CSS, using variables enables the passing of values from JavaScript to animations. For instance:

.p1, .p2 {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: var(--m, 0%);
    width: var(--w, 100%);
  }
  to {
    margin-left: 0%;
    width: 100%;
  }
}
Copy after login

Implementation in JavaScript

Using JavaScript, you can then set these variables:

document.querySelector('.p2').style.setProperty('--m','100%');
document.querySelector('.p2').style.setProperty('--w','300%');
Copy after login

Example Usage

This will alter the animation of the element with the class "p2":

<p class="p1">
 This will not animate as the animation will use the default value set to the variable
</p>
<p class="p2">
  This will animate because we changed the CSS variable using JS
</p>
Copy after login

The above is the detailed content of How Can I Pass JavaScript Variables to CSS Animations?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template