Home >Web Front-end >CSS Tutorial >How to Dynamically Create CSS @-keyframes Animations Based on Server Responses?
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.
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); } }
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!