Home >Web Front-end >CSS Tutorial >How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 22:57:161093browse

How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

Dynamic Keyframe Values: Using JavaScript Variables in CSS

Question:

How can you dynamically set the rotation values of a Webkit keyframe animation using JavaScript variables?

Answer:

In CSS, you cannot directly insert JavaScript variables into keyframe animations. To achieve this, you need to create the CSS rules through JavaScript and insert them into the CSS Object Model (CSSOM).

Consider the following sample code:

@-webkit-keyframes rotate {
    0% {-webkit-transform: rotate(-10deg);}
    100% {-webkit-transform: rotate(10deg);}
}

#dog{
/*irrelevant settings*/
-webkit-animation: rotate 5s infinite alternate ease-in-out;
}

To dynamically set the rotation values, you can write a JavaScript function:

// Assume var dogValue = "20deg";
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
var keyframesRule = `@-webkit-keyframes rotate {
    0% {-webkit-transform: rotate(-${dogValue});}
    100% {-webkit-transform: rotate(${dogValue});}
}`;
styleElement.appendChild(document.createTextNode(keyframesRule));
document.head.appendChild(styleElement);

This code creates a new

By following this approach, you can dynamically set keyframe values using JavaScript variables, ensuring that the CSS rules are updated as you need them.

The above is the detailed content of How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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