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%);
}
to {
margin-left: 0%; width: 100%;
}
}
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!