Home > Web Front-end > CSS Tutorial > How Can I Use JavaScript Variables to Dynamically Set WebKit Keyframe Values?

How Can I Use JavaScript Variables to Dynamically Set WebKit Keyframe Values?

Susan Sarandon
Release: 2024-11-29 20:55:12
Original
702 people have browsed it

How Can I Use JavaScript Variables to Dynamically Set WebKit Keyframe Values?

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:

  1. Create the desired keyframe animation object using the window.document.createElement() method. This object will serve as a container for your keyframe definitions.
  2. Define the actual keyframes using the keyframes.insertRule() method. This method takes two parameters: the keyframe percentage and the CSS rules for that percentage.
  3. Insert the newly created keyframe animation into the CSSOM using the sheet.insertRule() method.

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);
}
Copy after login

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!

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