How to dynamically create '@-Keyframe' CSS animations?

前端 未结 9 1245
误落风尘
误落风尘 2020-11-27 03:42

I have a requirement to rotate a div and stop at a particular position ( The value will be received from the server).

I tried native JS to rotate and stop but it is

9条回答
  •  Happy的楠姐
    2020-11-27 04:20

    In JavaScript is it possible to access to the style sheet with document.styleSheets. Every sheet has a rule and/or cssRule list (browser depending) and a CSSStyleSheet.insertRule() method.

    This method allows you to add a new keyframe raw as a string:

    JavaScript

    function insertStyleSheetRule(ruleText)
    {
        let sheets = document.styleSheets;
    
        if(sheets.length == 0)
        {
            let style = document.createElement('style');
            style.appendChild(document.createTextNode(""));
            document.head.appendChild(style);
        }
    
        let sheet = sheets[sheets.length - 1];
        sheet.insertRule(ruleText, sheet.rules ? sheet.rules.length : sheet.cssRules.length);
    }
    
    document.addEventListener("DOMContentLoaded", event =>
    {
        insertStyleSheetRule("@keyframes spinIt { 0% { transform: rotate(-20deg); } 100% { transform: rotate(20deg); } }");
    
        insertStyleSheetRule("#box { " + 
            "animation: spinIt 1s infinite alternate cubic-bezier(0.5,0,0.5,1); " + 
            "width: 64px; height: 64px; background-color: red; border: 4px solid black; " + 
        "}");
    });
    

    html

    demo: https://jsfiddle.net/axd7nteu/

提交回复
热议问题