Home >Web Front-end >CSS Tutorial >How to Dynamically Create CSS @-keyframes Animations Based on Server Responses?

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

DDD
DDDOriginal
2024-11-12 22:54:02633browse

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);
    }
}

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);

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!

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