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

前端 未结 9 1213
误落风尘
误落风尘 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条回答
  • 2020-11-27 04:28

    Let me share an updated (2019) answer to this.

    Yes, it's possible without Javascript using CSS Variables (supported by all modern browsers).

    --lightScaleStart: 0.8;
    
    .light {
        animation: grow 2s alternate infinite ease-in-out;
    }
    
    .light.yellow {
        --lightScaleEnd: 1.1;
    }
    
    .light.red {
        --lightScaleEnd: 1.2;
    }
    
    @keyframes grow {
      from {
        transform: scale(var(--lightScaleStart));
      }
      to {
        transform: scale(var(--lightScaleEnd));
      }
    }
    

    See demo on Codepen Dynamic CSS Animations with CSS Variables

    Edit: Here's a CSS Tricks article about it too.

    0 讨论(0)
  • 2020-11-27 04:30

    You can insert stylesheet rules dynamically to override previous styles in the head. This helps avoid adding yet another library for a single task.

    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);
    
    0 讨论(0)
  • 2020-11-27 04:33

    You can change the style in CSSKeyframeRule, and this works fine for me in Chrome, just as the code below. Hope this will help:)

    <html>
    
    <head>
    	<style>
    		#text {
    			display: inline-block;
    		}
    	</style>
    </head>
    
    <body>
    	<div id="text">TEXT</div>
    	<script>
    	
    		// Dynamically create a keyframe animation
    		document.styleSheets[0].insertRule('\
    			@keyframes anim {\
    				from { transform: rotateZ(0deg);   }\
    				to   { transform: rotateZ(360deg); }\
    			}'
    		);
    		var div = document.getElementById('text');
    		div.style.animation = 'anim 1s linear forwards';
    		
    		// This function will change the anim
    		function stopAtSomeDeg(d) {
    			var ss = document.styleSheets[0];
    			var anim;
    			for (var i in ss.cssRules) {
    				// Find your animation by name
    				if (ss.cssRules[i].name === 'anim') {
    					anim = ss.cssRules[i];
    					break;
    				}
    			}
    			var stopFrame = anim.cssRules[1]; // This indicates the second line of "anim" above.
    			
    			// Change any attributes
    			stopFrame.style.transform = 'rotateZ(' + d + 'deg)';
    		}
    		
    		stopAtSomeDeg(180);
    	</script>
    </body>
    </html>

    0 讨论(0)
提交回复
热议问题