How to Dynamically Create CSS @-keyframes Animations Based on Server Responses?

DDD
Release: 2024-11-12 22:54:02
Original
594 people have browsed it

How to Dynamically Create CSS @-keyframes Animations Based on Server Responses?

Dynamically Generating CSS @-keyframes Animations

Scenario

You need to rotate a div and stop it at a specific position determined by a server response. Using native JS for rotation and stopping consumes excessive CPU resources.

Solution

Leverage CSS animations for rotation, but require a dynamically defined class to specify the stop position:

@-webkit-keyframes spinIt {
    100% {
        -webkit-transform: rotate(A_DYNAMIC_VALUE);
    }
}
@-moz-keyframes spinIt {
    100% {
        -webkit-transform: rotate(A_DYNAMIC_VALUE);
    }
}
Copy after login

Implementation

Dynamically insert stylesheet rules to override previous styles:

var style = document.createElement('style');
style.type = 'text/css';
var keyFrames = '\
@-webkit-keyframes spinIt {\
    100% {\
        -webkit-transform: rotate(A_DYNAMIC_VALUE);\
    }\
}\
@-moz-keyframes spinIt {\
    100% {\
        -webkit-transform: rotate(A_DYNAMIC_VALUE);\
    }\
}';
style.innerHTML = keyFrames.replace(/A_DYNAMIC_VALUE/g, "180deg");
document.getElementsByTagName('head')[0].appendChild(style);
Copy after login

Replace A_DYNAMIC_VALUE with the desired stop position (e.g., "180deg") and append the style element to the head of the document to apply the animation dynamically.

The above is the detailed content of How to Dynamically Create CSS @-keyframes Animations Based on Server Responses?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template