Home > Web Front-end > CSS Tutorial > How Can I Dynamically Customize CSS Animation Parameters?

How Can I Dynamically Customize CSS Animation Parameters?

Patricia Arquette
Release: 2024-11-29 07:29:14
Original
844 people have browsed it

How Can I Dynamically Customize CSS Animation Parameters?

Customizing CSS Animations with Parameterized Values

The provided CSS animation sets the duration and parameters for an element sliding in from the left. However, what if you want to customize these parameters dynamically based on the context?

One way to achieve this is by utilizing CSS variables. Here's how:

p {
animation-duration: 3s;
animation-name: slidein;
}

@keyframes slidein {
from {

margin-left: var(--m, 0%);
width: var(--w, 100%);
Copy after login

}

to {

margin-left: 0%;
width: 100%;
Copy after login

}
}

Now, using JavaScript, you can set the values for --m (margin-left) and --w (width) like this:

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

This enables you to control the animation parameters for specific elements dynamically.

As an example, consider two paragraphs with class names "p1" and "p2":

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

This will not animate as the animation will use the default value set to the variable


This will animate because we changed the CSS variable using JS

The first paragraph will not animate because it uses the default values for --m and --w. The second paragraph, however, will animate according to the customized parameters set in JavaScript.

The above is the detailed content of How Can I Dynamically Customize CSS Animation Parameters?. 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