Use JavaScript to Set Webkit Keyframes Values with Variables
You're facing a common challenge when trying to utilize random values generated in JavaScript for CSS animations. JavaScript variables cannot be directly injected into CSS keyframes.
Instead, you need to create the CSS rules dynamically through JavaScript and insert them into the CSS Object Model (CSSOM).
Dynamic Keyframe Creation
Follow these steps to create and manipulate keyframes dynamically:
Example
Here's an example that dynamically creates and overwrites an existing keyframe animation with random rotation values:
function createRandomRotation(dogValue) { // Create the keyframe animation object let rotateAnimation = window.document.createElement('style'); // Define the actual keyframes rotateAnimation.innerHTML = ` @-webkit-keyframes rotate { 0% {-webkit-transform: rotate(-${dogValue});} 100% {-webkit-transform: rotate(${dogValue});} } #dog { -webkit-animation: rotate 5s infinite alternate ease-in-out; } `; // Insert the keyframe animation into the CSSOM window.document.head.appendChild(rotateAnimation); }
Usage
You can use this function to continually update the rotation keyframes with random values. For instance, you could have a button that triggers a click event to generate new random degrees and update the keyframes accordingly.
Remember to replace dogValue with your randomly generated degree value.
The above is the detailed content of How Can I Use JavaScript Variables to Dynamically Set WebKit Keyframe Values?. For more information, please follow other related articles on the PHP Chinese website!