Home > Web Front-end > CSS Tutorial > Can JavaScript Dynamically Modify CSS Animation Parameters?

Can JavaScript Dynamically Modify CSS Animation Parameters?

Mary-Kate Olsen
Release: 2024-12-07 16:04:12
Original
843 people have browsed it

Can JavaScript Dynamically Modify CSS Animation Parameters?

Parameterizing CSS Animations with JavaScript

Question:

In the provided CSS animation code, is it possible to dynamically modify the margin-left and width values through JavaScript?

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

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%; 
  }

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

Answer:

Yes, there is a way to pass values to CSS animations from JavaScript by utilizing CSS variables.

.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

JavaScript:

// Set CSS variables using JavaScript
document.querySelector('.p2').style.setProperty('--m','100%');
document.querySelector('.p2').style.setProperty('--w','300%');
Copy after login

This approach allows you to control the animation parameters dynamically through JavaScript, enabling greater flexibility and customization.

The above is the detailed content of Can JavaScript Dynamically Modify 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