Home >Web Front-end >CSS Tutorial >How Can I Pass JavaScript Variables to CSS Animations?
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.
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%; } }
Using JavaScript, you can then set these variables:
document.querySelector('.p2').style.setProperty('--m','100%'); document.querySelector('.p2').style.setProperty('--w','300%');
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>
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!