Home > Web Front-end > CSS Tutorial > How to Dynamically Create CSS Animations with '@-Keyframes'?

How to Dynamically Create CSS Animations with '@-Keyframes'?

Patricia Arquette
Release: 2024-11-15 02:20:02
Original
1050 people have browsed it

How to Dynamically Create CSS Animations with '@-Keyframes'?

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:

  1. Create a style element:

    var style = document.createElement('style');
    style.type = 'text/css';
    Copy after login
  2. 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);\
        }\
    }';
    Copy after login
  3. Replace the placeholder with the desired angle:

    style.innerHTML = keyFrames.replace(/A_DYNAMIC_VALUE/g, "180deg");
    Copy after login
  4. Insert the style into the document head:

    document.getElementsByTagName('head')[0].appendChild(style);
    Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template