How to dynamically change css keyframes in js

藏色散人
Release: 2023-01-30 09:55:38
Original
1627 people have browsed it

JS method to dynamically change css keyframes: 1. Obtain the link style sheet and style style sheet introduced on the web page through the "document.styleSheets" interface; 2. Insert through the "insertRule(rule,index)" method The new "@keyframes" rule will do.

How to dynamically change css keyframes in js

The operating environment of this tutorial: Windows 10 system, CSS3 version, DELL G3 computer

How to dynamically change css keyframes with js?

js dynamically modify @keyframes rules in CSS3

## Here is a small demo of a clock. The material given is as follows:


How to dynamically change css keyframes in js The initial direction of the second hand is towards 6 o'clock. We set the @keyframes rule for the second hand to rotate once

	@keyframes rotate {
		   from{
		   	   transform: rotate(0deg);
		   }
           to{
               transform: rotate(360deg);
           }
	}
Copy after login
This setting can rotate one week normally, but if we change the initial position of the second hand, for example, set it to the 12 o'clock direction

	transform: rotate(180deg);
Copy after login
, then the previous @keyframes rule needs to be converted from 0deg=>360deg to 180deg=> 540deg

Then the problem arises. This modification is not dynamic. We cannot modify the @keyframes rules in the style every time

We need to use our js here

First of all Obtain the link style sheet and style style sheet introduced on the web page through the document.styleSheets interface

	var style = document.styleSheets[0];
Copy after login

How to dynamically change css keyframes in js Then insert a new @keyframes rule through the insertRule(rule,index) method

	var newdeg = 540;
	style.insertRule("@keyframes secondrotate {to{transform: rotate(" + newdeg + "deg);}}",4);
Copy after login
In this way, the effect we need is achieved

How to dynamically change css keyframes in js

Recommended learning: "

css video tutorial"

The above is the detailed content of How to dynamically change css keyframes in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template