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%; } }
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%; } }
JavaScript:
// Set CSS variables using JavaScript document.querySelector('.p2').style.setProperty('--m','100%'); document.querySelector('.p2').style.setProperty('--w','300%');
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!