Dynamically Creating '@-Keyframe' CSS Animations
To achieve dynamic customization of CSS animations, you can create and insert stylesheet rules on the fly. This approach allows you to override existing styles and control the animation endpoints based on received values.
Solution:
Create a style element:
var style = document.createElement('style'); style.type = 'text/css';
Construct the keyframes definition:
var keyFrames = '\ @-webkit-keyframes spinIt {\ 100% {\ -webkit-transform: rotate(A_DYNAMIC_VALUE);\ }\ }\ @-moz-keyframes spinIt {\ 100% {\ -webkit-transform: rotate(A_DYNAMIC_VALUE);\ }\ }';
Replace the placeholder with the desired angle:
style.innerHTML = keyFrames.replace(/A_DYNAMIC_VALUE/g, "180deg");
Insert the style into the document head:
document.getElementsByTagName('head')[0].appendChild(style);
This will dynamically create and apply a CSS animation with the specified rotation angle. You can adjust the A_DYNAMIC_VALUE placeholder as needed to rotate based on server-provided values.
By leveraging this technique, you can optimize performance by avoiding native JS animations that can consume significant CPU resources. The dynamic creation of stylesheet rules provides the flexibility to customize animations on the fly, enhancing the user experience without additional external libraries.
The above is the detailed content of How to Dynamically Create CSS Animations with '@-Keyframes'?. For more information, please follow other related articles on the PHP Chinese website!