Как изменить keyframes js

I'm using #progressBar{ background-color: #247BA0; width: 150px; padding: 10px; border-radius: 5px; animation: progressBar 3s ease; animation-fill-mode:both; text-align: cente...

I guess we are in the territory of CSS+JS = CJSSS thats lot of Ss to handle tbh. JS deals with Document object model and CSS deals with CSS object model. Browser object model deals with both of these.

That’s being said JS have no interaction with CSSOM. What we see on screen is BOM taking the two and painting it on screen. It is when its painted aka DOM is represented Js is able to access and manipulate objects.

With above in mind when we change style values with JS e.g. element.style.height=100% it is happening after the fact widely known as computed value.

By computed it refers to what got painted on screen so element.height would return hight in pixels not the CSS rule from which it was painted that being percentage.

Thus when we are intending to change @keyframe we are intending to manipulate CSS rule before the fact not after the fact. thats problem no 1.

BOM only provides set number of CSS style properties to be manipulated through style function e.g. height color etc It does not include @keyframe in that set.

so we have to do some leg work to handle it after the fact.

root = document.documentElement;

 
 setTimeout(function(){ root.style.setProperty('--change', 30 + "px"); }, 5000);
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 


@keyframes progressBar {
 0% { width: 0; }
100% { width: var(--change); }
}
<div id="progressBar"></div>

So here is my solution allow me to introduce CSS Variables

I have created a CSS variable in CSSOM globle scope

:root {
      --change: 280px;
    }

then have accessed the same with in CSS. Benefit is when ever the value of variable is changed in root it will be automatically be represented where ever the variable is called.

 @keyframes progressBar {
     0% { width: 0; }
    100% { width: var(--change); }
    }

No we need to access this in after the fact. I have used document.documentElement to grab the whole document as an element including all the css that is in it.
then I have used style.setProperty to modify the modifies an existing CSS property in a CSS declaration block. Keyword declaration block not the computed painted block.

root.style.setProperty('--change', 30 + "px");

Above is changing the property of the document which is set in global scope of CSSOM and it has no sub properties etc. We still cannot access rules e.g. root.style.setProperty(‘@keyframes progressBar’, 30 + «px») simply wont work.

final example to use it as before the fact.

root = document.documentElement;

 
 root.style.setProperty('--change', 30 + "px"); 
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 


@keyframes progressBar {
 0% { width: 0; }
100% { width: var(--change); }
}
<div id="progressBar"></div>

I have just put set time out function to show how it works. Obviously this time with out set timeout.

KEY TAKE AWAY.
manipulating CSS block after the fact wont rerun the animation again as seen in the first example unless you run another set of function that reverses every thing then redoes it. Depends on your context.

manipulating CSS block before the fact will consider JS manipulation as considered value as shown in the second example.

By context I mean what ever you intend to do really as sown in example below using set time out we are changing css variable after 3 seconds obviously animation is ran twice to but on second run bar goes even longer. so CJSSS alo needs you context.

root = document.documentElement;

 
 setTimeout(function(){ root.style.setProperty('--change', 500 + "px"); }, 3000);
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
animation-iteration-count: 2;
} 


@keyframes progressBar {
 0% { width: 0; }
50% { width: var(--change); }
100% { width: 0; }
}
<div id="progressBar"></div>

Hope answer gives you enough head ways to move forward.

    Table of contents

  • How can I set a CSS keyframes in Javascript?
  • Dynamic CSS Keyframes in JavaScript
  • How do I change @keyframes using JS? [duplicate]
  • Changing CSS keyframes through Javascript
  • @keyframes
  • How can I call CSS keyframe using Javascript? without jQuery
  • How to write css keyframes in javascript

How can I set a CSS keyframes in Javascript?

.cylon-eye {
  background-color: yellow;
  background-image: linear-gradient( to right, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.9) 75%);
  color: none;
  height: 100%;
  width: 20%;
  animation: 4s linear 0s infinite alternate move-eye;
}
@keyframes move-eye {
  from {
    margin-left: -20%;
  }
  to {
    margin-left: 100%;
  }
}
<script type="text/javascript">
function appendStyle(styles) {
var css = document.createElement('style');
css.type = 'text/css';

if (css.styleSheet) css.styleSheet.cssText = styles;
else css.appendChild(document.createTextNode(styles));

document.getElementsByTagName("head")[0].appendChild(css);

}

var styles = '#cylon-eye { background-color: yellow; background-image: linear-gradient(to right,rgba(255,255,255, 0.9) 25%,rgba(255,255,255, 0.1) 50%,rgba(255,255,255, 0.9) 75%); color: none; height: 100%; width: 20%;animation: 4s linear 0s infinite alternate move-eye; z-index: 10;}';
var keyFrames = '
@keyframes move-eye {
  from {
    margin-left: -20%;
  }

  to {
    margin-left: 100%;
  }
}';

window.onload = function() { appendStyle(styles) };
</script>
let dynamicStyles = null;

function addAnimation(body) {
  if (!dynamicStyles) {
    dynamicStyles = document.createElement('style');
    dynamicStyles.type = 'text/css';
    document.head.appendChild(dynamicStyles);
  }

  dynamicStyles.sheet.insertRule(body, dynamicStyles.length);
}

addAnimation(`
      @keyframes move-eye { 
         from {
           margin-left: -20%;
         }
        to {
          margin-left: 100%;
        }
      }
    `);



var element = document.createElement("div");
element.className = "cylon-eye";
element.style.height = "50px";
element.style.width = "50px";
element.style.backgroundImage = "linear-gradient(to right,rgba(255, 0, 0, 0.1) 25%,rgba(255, 0, 0) 50%,rgba(255, 0, 0, 0.1) 75%)";
element.style.animation = "4s linear 0s infinite alternate move-eye";

document.body.appendChild(element);
var element = document.createElement("div");
element.className = "cylon-eye";
element.style.height = "50px";
element.style.width = "50px";
document.body.appendChild(element);
.cylon-eye {
  background-color: yellow;
  background-image: linear-gradient(to right, rgba(255, 0, 0, 0.9) 25%, rgba(255, 0, 0, 0.1) 50%, rgba(255, 0, 0, 0.9) 75%);
  color: none;
  height: 100%;
  width: 20%;
  animation: 4s linear 0s infinite alternate move-eye;
}

@keyframes move-eye {
  from {
    margin-left: -20%;
  }
  to {
    margin-left: 100%;
  }
}
var style = document.createElement('style');
style.type = 'text/css';
var keyFrames = '
@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%; 
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}';

document.getElementsById('slideDiv')[0].appendChild(style);
document.styleSheets[0].cssRules
const loading = document.querySelector('.loading');
const keyFrames = document.createElement("style");

keyFrames.innerHTML = `
  @keyframes loading {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .loading {
    animation: loading 1s ease infinite;
  }
`;

loading.appendChild(keyFrames);
.loading {
  width: 100px;
  height: 100px;
  background-size: cover;
  background-image: url('https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.24ways.org%2F2009%2F15%2Fassets%2Fimg%2Fspinner.png&f=1&nofb=1');
  background-repeat: no-repeat;
}
<!doctype html>
<html>
  <head>
    <title>Keyframes in js</title>
  </head>
  <body>
    <div class="loading"></div>
  </body>
</html>

Dynamic CSS Keyframes in JavaScript

mkdir dynamic-animation-tutorial
cd dynamic-animation-tutorial
touch tutorial.js
npm install [email protected] [email protected] 
[email protected] [email protected] 
[email protected]
<html>
  <head>
    <!-- Your page starts of like this-->
  </head>
  <body>
   ...
  </body>
</html> 
<html>
  <head>
    <!-- We dynamically create a <style> 
    tag with a CSS keyframe string -->
    <style>
        <!-- You created this style string in code 
        and insert it into your <head> -->
        @keyframe my-generated-keyframe { ... }
    </style>
  </head>
  <body>
   ...
  </body>
</html>  
var stringifyObject = require('stringify-object')
var createKeyframe = require('create-keyframe')
var insertCSS = require('insert-styles')
var jsonDisplay = document.createElement('div')
jsonDisplay.style.whiteSpace = 'pre'
jsonDisplay.style.borderRadius = '5px'
jsonDisplay.style.backgroundColor = '#F6F6F6'
jsonDisplay.style.color = '#2B2B2B'
jsonDisplay.style.maxWidth = '500px'
jsonDisplay.style.fontSize = '24px'
jsonDisplay.style.marginTop = '15px'
jsonDisplay.style.fontFamily = 'Avenir'
jsonDisplay.style.padding = '5px'
jsonDisplay.style.boxSizing = 'border-box'
var userMessage = document.createElement('span')
userMessage.style.fontSize = '48px'
userMessage.style.display = 'block'
userMessage.innerHTML = 'Great Job!'
var createAnimationButton = 
  document.createElement('button')
createAnimationButton.style.fontSize = '24px'
createAnimationButton.style.cursor = 'pointer'
createAnimationButton.onclick = generateKeyframe
createAnimationButton.innerHTML = 'Generate keyframe'
var appContainer = document.querySelector(
 '#generate-keyframe-animation-tutorial'
) || document.body
appContainer.appendChild(userMessage)
appContainer.appendChild(createAnimationButton)
appContainer.appendChild(jsonDisplay)
function createRandomColors () {
  return [
    (Math.random() * 255).toFixed(0),
    (Math.random() * 255).toFixed(0),
    (Math.random() * 255).toFixed(0),
    1
  ]
}
function generateKeyframe () {
  var randomColors = createRandomColors()

  var shakeDistance = Number(
   (Math.random() * 70).toFixed(0)
  ) + 30

  var cssKeyframe
  cssKeyframe = {
    0: {
      color: 'black'
    },
    20: { transform: `translateX(${shakeDistance}px)` },
    60: { transform: `translateX(-${shakeDistance}px)` },
    75: {
      color: `rgba(${randomColors.join(', ')})`
    },
    100: { color: 'black' }
  }
  var keyframeObj = createKeyframe(cssKeyframe)
  insertCSS(keyframeObj.css, {id: 'animaton-tutorial-keyframe'})

  jsonDisplay.innerHTML = `@keyframe ${keyframeObj.name} ` +
   stringifyObject(cssKeyframe, {indent: '  '})
  userMessage.style.animation = keyframeObj.name + ' ease 3s infinite'
}

generateKeyframe()

How do I change @keyframes using JS? [duplicate]

#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 
@keyframes progressBar {
 0% { width: 0; }
100% { width: 280px; }
}
:root {
    --my-start-width: 0;
    --my-end-width: 280px;
}

...

@keyframes progressBar {
    0% { width: var(--my-start-width); }
    100% { width: var(--my-end-width); }
}

//set property: 

document.documentElement.style
    .setProperty('--my-variable-name', '100px');

//get property

getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name'); // returns value

root = document.documentElement;

 
 setTimeout(function(){ root.style.setProperty('--change', 30 + "px"); }, 5000);
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 


@keyframes progressBar {
 0% { width: 0; }
100% { width: var(--change); }
}
<div id="progressBar"></div>
:root {
      --change: 280px;
    }
 @keyframes progressBar {
     0% { width: 0; }
    100% { width: var(--change); }
    }
root.style.setProperty('--change', 30 + "px");
root = document.documentElement;

 
 root.style.setProperty('--change', 30 + "px"); 
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 


@keyframes progressBar {
 0% { width: 0; }
100% { width: var(--change); }
}
<div id="progressBar"></div>
root = document.documentElement;

 
 setTimeout(function(){ root.style.setProperty('--change', 500 + "px"); }, 3000);
:root {
  --change: 280px;
}
#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
animation-iteration-count: 2;
} 


@keyframes progressBar {
 0% { width: 0; }
50% { width: var(--change); }
100% { width: 0; }
}
<div id="progressBar"></div>

Changing CSS keyframes through Javascript

@keyframes changeColor {
  0% {
    color: transparent;
  }
  50% {
    color: black;
  }
}
@-moz-keyframes changeColor {
  0% {
    color: yellow;
  }
  50% {
    color: red;
  }
}
@-webkit-keyframes changeColor {
  0% {
    color: yellow;
  }
  50% {
    color: red;
  }
}

@-o-keyframes changeColor {
  0%{
    color: yellow;
  }
  50% {
    color: red;
  }
}
var supportedFlag = $.keyframe.isSupported();
$.keyframe.define([{
    name: 'roll-clockwise',
    '0%': {
        'color' : 'green'
    },
    '100%': {
        'color' : 'yellow'
    }
    }
]);
$("p").playKeyframe({
    name: 'changeColor',
    duration: 2000
});
// Note that this is psuedocode and will need to be refactored slightly to better fit your own code
// variables storing color values
var colorA = 'red', 
    colorB = 'blue';
//store element you are changing in a variable
const ELEMENT = document.querySelector('element'); 
function changeColors() {
    // store current color value of ELEMENT in a variable called currentColor
    let currentColor = ELEMENT.style.color; 
    // if color is currently A, switch to B
    if (currentColor == colorA) { 
        ELEMENT.style.color = colorB;
    }
    // else, switch to A
    else { 
        ELEMENT.style.color = colorA;
    }
}
// call set interval to alternate colors with same timing value as set in transition attribute in CSS
setInterval(changeColors, 500); 

@keyframes

@keyframes slidein {
  from {
    transform: translateX(0%);
  }

  to {
    transform: translateX(100%);
  }
}
@keyframes identifier {
  0% { top: 0; left: 0; }
  30% { top: 50px; }
  68%, 72% { left: 50px; }
  100% { top: 100px; left: 100%; }
}
@keyframes identifier {
  0% { top: 0; }
  50% { top: 30px; left: 20px; }
  50% { top: 10px; }
  100% { top: 0; }
}
@keyframes important1 {
  from { margin-top: 50px; }
  50%  { margin-top: 150px !important; } /* ignored */
  to   { margin-top: 100px; }
}

@keyframes important2 {
  from { margin-top: 50px;
         margin-bottom: 100px; }
  to   { margin-top: 150px !important; /* ignored */
         margin-bottom: 50px; }
}
@keyframes <keyframes-name> {
  <keyframe-block-list>
}where <keyframes-name> = <custom-ident> | <string><keyframe-block-list> = <keyframe-block>+where <keyframe-block> = <keyframe-selector># {
  <declaration-list>
}where <keyframe-selector> = from | to | <percentage>
@keyframes slidein {n  from {n    transform: translateX(0%);n  }nn  to {n    transform: translateX(100%);n  }n}n
@keyframes identifier {n  0% { top: 0; left: 0; }n  30% { top: 50px; }n  68%, 72% { left: 50px; }n  100% { top: 100px; left: 100%; }n}n
@keyframes identifier {n  0% { top: 0; }n  50% { top: 30px; left: 20px; }n  50% { top: 10px; }n  100% { top: 0; }n}n
@keyframes important1 {n  from { margin-top: 50px; }n  50%  { margin-top: 150px !important; } /* ignored */n  to   { margin-top: 100px; }n}n[email protected] important2 {n  from { margin-top: 50px;n         margin-bottom: 100px; }n  to   { margin-top: 150px !important; /* ignored */n         margin-bottom: 50px; }n}n
@keyframes <keyframes-name> {n  <keyframe-block-list>n}where <keyframes-name> = <custom-ident> | <string><keyframe-block-list> = <keyframe-block>+where <keyframe-block> = <keyframe-selector># {n  <declaration-list>n}where <keyframe-selector> = from | to | <percentage>

How can I call CSS keyframe using Javascript? without jQuery

div#b {
  -webkit-animation: blink 1s linear infinite alternate;
}

@-webkit-keyframes blink {
  0% {
    opacity: 0.0
  }
  ;
  100% {
    opacity: 1.0
  }
  ;
}
<div id="b">Blinking</div>
 <tr>
  <th id="1">Mon</th>
  <th id="2">Tue</th>
  <th id="3">Wed</th>
  <th id="4">Thu</th>
  <th id="5">Fri</th>
</tr>
var blinking = document.getElementById("b");
b.className = "blinking";


function RemoveBlink() {
  var blinking = document.getElementById("b");
  b.className = "";
}
div#b {
  
}

.blinking {
  -webkit-animation: blink 1s linear infinite alternate;
}

@-webkit-keyframes blink {
  0% {
    opacity: 0.0
  }
  ;
  100% {
    opacity: 1.0
  }
  ;
}
<div id="b">Blinking</div>

<button onclick="RemoveBlink()">REMOVE BLINK</button>

How to write css keyframes in javascript

<style>

#one
{
    width:96px;
    height:0px;
    left:204px;
    top:65px;
    z-index:2;
    position:absolute;
    background-color:#FFF;
    animation:myfirst 2s;
    -moz-animation:myfirst 2s; /* Firefox */
    -webkit-animation:myfirst 2s; /* Safari and Chrome */
    -o-animation:myfirst 2s; /* Opera */
}

@keyframes myfirst
{
from {height:188px; }
to {height:10px;}
}

 /* Firefox */
@-moz-keyframes myfirst
{
from {height:188px; }
to {height:10px;}
}

 /* Safari and Chrome */
@-webkit-keyframes myfirst
{
from {height:188px; }
to {height:10px;}
}

 /* Opera */
@-o-keyframes myfirst
{
from {height:188px; }
to {height:10px;}
}

</style>
var p1 = document.getElementById('one');
    p1.style.width = "96px";
    p1.style.height = "0px";
    p1.style.left = "204px";
    p1.style.zIndex = "2";
    p1.style.position = "absolute";
    p1.style.backgroundColor = "white";
    p1.style.animation = "one 2s";
    p1.style.WebkitAnimation = "one 2s";
    p1.style.MozAnimation = "one 2s";
    p1.style.oAnimation = "one 2s";
var styleSheetElement = document.createElement("style"), customStyleSheet;

document.head.appendChild(styleSheetElement);

// get the appended stylesheet
// you can use the returned node from the appendage like this
// customStyleSheet = (document.head.appendChild(styleSheetElement)).sheet
customStyleSheet = document.styleSheets[0];

// Make sure you apply the appropriate css rule name for the browser, as
// "@keyframes" the standard while different browser has their own rule name
// example, if you're using Chrome you should use "@-webkit-keyframes" instead.
// the browser will throw an error if you provided the wrong css rule name
customStyleSheet.insertRule("@keyframes myfirst { from {height:188px; } to {height:10px;}}");

Next Lesson PHP Tutorial

With CSS variables: You can use the pseudo :root of the element to declare a css variable within the css rules, then manipulate that variable using Javascript.

:root {--variable-name:property;} which is basically the root element of the document <html>. Then change the value of the CSS root variable/s using JS with:

element.style.setProperty('--variable-name','value'). Pass the declared root variable --variable-name as the name and assign the new value. Then in your @keyframes css rules, add the root variable name, like: from: { top: var(--top-position)}, to the property within the offset @keyframe rule. Example:

:root {
  --top-position-start: 0px;
  --left-position-start: 0px;
  --top-position-end: 200px;
  --left-position-end: 200px;
}

.element {
  top: var(--top-position-start);
  left: var(--left-position-start);
  animation: movePos 1s ease-in;
}

@keyframes movePos {
  from: {
    top: var(--top-position-start);
    left: var(--left-position-start);
  } 
  to: {
    top: var(--top-position-end);
    left: var(--left-position-end);
  }
}

Then the JS would like something like:

let ran = getRandomInt(99);
let skew = ran + getRandomInt(10);
root.style.setProperty('--top-position-end', `${ran}vw`);
root.style.setProperty('--left-position-end', `${skew}vw`);

By using the CSS variable on the root element, you are able to pass it along to the @keyframes event.

See the following working example using randomly placed div using CSS left and background-color:rgb()(red, green, blue) passed using the html:root style to @keyframes within CSS.

let root = document.documentElement;
let rain = document.querySelectorAll('.drop');

function getMaxInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function getMinMaxInt(min, max) {
  return Math.random() * (max - min) + min;
}
// set an interval to drop the div from randomly positioned view widths on the screen
setInterval(() => {
  let ran = getMaxInt(86);
  let skew = ran + getMaxInt(10);
  let circle = `${getMinMaxInt(3,15)}px`;
  root.style.setProperty('--keyframeLeftStart', `${ran}vw`);
  root.style.setProperty('--keyframeLeftEnd', `${skew}vw`);  
  root.style.setProperty('--animationDuration', `${ getMaxInt(2500)}ms`); 
  root.style.setProperty('--width', circle);
  root.style.setProperty('--height', circle);
  root.style.setProperty('--red', getMinMaxInt(100, 255));
  root.style.setProperty('--green', getMinMaxInt(100, 255));
  root.style.setProperty('--blue', getMinMaxInt(100, 255));
}, getMaxInt(3500))
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

/* here we define some css variables for the document :root 
   essentially, these will be the first iteration of the elements style
   then JS will take voer and set the values from script */
:root {
  --keyframeTop: 0;
  --keyframeBottom: 98vh;
  --keyframeLeftStart: 2vw;
  --keyframeLeftEnd: 10vw;
  --animationDuration: 1s;
  --width: 5px;
  --height: 5px;
  --red: 100;
  --green: 100;
  --blue: 100;
}

body {
  width: 100vw;
  height: 100vh;
  background-color: #000;
}

#main {
  width: calc(100vw - var(--width));
  height: calc(100vh - var(--height));
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.drop {
  width: var(--width);
  height: var(--height);
  border-radius: 50%;
  position: absolute;
  animation: dropping var(--animationDuration) ease-in infinite;
  top: var(--keyframeTop);
  left: var(--keyframeLeftStart);
  background-color: rgb(var(--red),var(--green), var(--blue));
}

@keyframes dropping {
  0% {
    top: var(--keyframeTop);
    left: var(--keyframeLeftStart);
    background-color: rgb(var(--red),var(--green), var(--blue));
  }
  50% {
    background-color: rgb(var(--green),var(--blue), var(--red));
  }
  100% {
    top: var(--keyframeBottom);
    left: var(--keyframeLeftEnd);
    background-color: rgb(var(--blue),var(--red), var(--green));
  }
}
<div id="main">
    <div class="drop"></div>
</div>

With CSS variables: You can use the pseudo :root of the element to declare a css variable within the css rules, then manipulate that variable using Javascript.

:root {--variable-name:property;} which is basically the root element of the document <html>. Then change the value of the CSS root variable/s using JS with:

element.style.setProperty('--variable-name','value'). Pass the declared root variable --variable-name as the name and assign the new value. Then in your @keyframes css rules, add the root variable name, like: from: { top: var(--top-position)}, to the property within the offset @keyframe rule. Example:

:root {
  --top-position-start: 0px;
  --left-position-start: 0px;
  --top-position-end: 200px;
  --left-position-end: 200px;
}

.element {
  top: var(--top-position-start);
  left: var(--left-position-start);
  animation: movePos 1s ease-in;
}

@keyframes movePos {
  from: {
    top: var(--top-position-start);
    left: var(--left-position-start);
  } 
  to: {
    top: var(--top-position-end);
    left: var(--left-position-end);
  }
}

Then the JS would like something like:

let ran = getRandomInt(99);
let skew = ran + getRandomInt(10);
root.style.setProperty('--top-position-end', `${ran}vw`);
root.style.setProperty('--left-position-end', `${skew}vw`);

By using the CSS variable on the root element, you are able to pass it along to the @keyframes event.

See the following working example using randomly placed div using CSS left and background-color:rgb()(red, green, blue) passed using the html:root style to @keyframes within CSS.

let root = document.documentElement;
let rain = document.querySelectorAll('.drop');

function getMaxInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function getMinMaxInt(min, max) {
  return Math.random() * (max - min) + min;
}
// set an interval to drop the div from randomly positioned view widths on the screen
setInterval(() => {
  let ran = getMaxInt(86);
  let skew = ran + getMaxInt(10);
  let circle = `${getMinMaxInt(3,15)}px`;
  root.style.setProperty('--keyframeLeftStart', `${ran}vw`);
  root.style.setProperty('--keyframeLeftEnd', `${skew}vw`);  
  root.style.setProperty('--animationDuration', `${ getMaxInt(2500)}ms`); 
  root.style.setProperty('--width', circle);
  root.style.setProperty('--height', circle);
  root.style.setProperty('--red', getMinMaxInt(100, 255));
  root.style.setProperty('--green', getMinMaxInt(100, 255));
  root.style.setProperty('--blue', getMinMaxInt(100, 255));
}, getMaxInt(3500))
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

/* here we define some css variables for the document :root 
   essentially, these will be the first iteration of the elements style
   then JS will take voer and set the values from script */
:root {
  --keyframeTop: 0;
  --keyframeBottom: 98vh;
  --keyframeLeftStart: 2vw;
  --keyframeLeftEnd: 10vw;
  --animationDuration: 1s;
  --width: 5px;
  --height: 5px;
  --red: 100;
  --green: 100;
  --blue: 100;
}

body {
  width: 100vw;
  height: 100vh;
  background-color: #000;
}

#main {
  width: calc(100vw - var(--width));
  height: calc(100vh - var(--height));
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.drop {
  width: var(--width);
  height: var(--height);
  border-radius: 50%;
  position: absolute;
  animation: dropping var(--animationDuration) ease-in infinite;
  top: var(--keyframeTop);
  left: var(--keyframeLeftStart);
  background-color: rgb(var(--red),var(--green), var(--blue));
}

@keyframes dropping {
  0% {
    top: var(--keyframeTop);
    left: var(--keyframeLeftStart);
    background-color: rgb(var(--red),var(--green), var(--blue));
  }
  50% {
    background-color: rgb(var(--green),var(--blue), var(--red));
  }
  100% {
    top: var(--keyframeBottom);
    left: var(--keyframeLeftEnd);
    background-color: rgb(var(--blue),var(--red), var(--green));
  }
}
<div id="main">
    <div class="drop"></div>
</div>

1. Диаграмма эффектов

Визуализации

2. Спрос

Перетащите форму, и положение движения маленькой точки также изменяется.

3. Технический анализ

Среди них мяч упражнений неоднократно многократно неоднократно перемещался с градиентом перехода, потому что переход может выполнять эффект градиента только один раз. Лучший способ повторить упражнения — это анимация.

4. Вопрос

@KeyFrames записан в CSS. В настоящее время вам нужно закончить операцию JS @KeyFrames, как JS работает @KeyFrames? Ниже день, когда я провел день, запрашивал информацию и собственное исследование, решая решение Совместим с сущностью решения IE

5. Операция JS @keyframes Решение

  1. Чтобы облегчить запрос и проблемы с производительностью, вызванные чрезмерным циркуляцией позже, вначале мы создали @KeyFrames через JS
// JS [email protected], мяч перемещается от позиционирования (10,10) к (10,10) на (100 100) позиций
const runkeyframes =` @keyframes ball-run{
    0%{
        left: 10px;
        top: 10px;
    }
    100%{
        left: 100px;
        top: 100px;
    }
}`
 // Создать этикетку стиля
const style = document.createElement('style');
 // установить атрибут стиля
style.type = 'text/css';
 // Напишите стиль ключевых кадров в стиле
style.innerHTML = runkeyframes;
 // задержит стиль стиля к тегке головы
document.getElementByTagName('head')[0].appendChild(style);
<style>
  .ball{
      width:10px;
      height:10px;
      border-radius:50%;
      background-color:#fff
  }
</style>
<!-Это этикетка и стиль мяча->
<div id="ball" class="ball" style="animaition: ball-run 10s infinite;"></div>
  1. JS Modify @KeyFrames
// Получить все стили стиля
 // Найти стиль стиля, соответствующий ключевым кадрам мяча
 // Получение метода: в соответствии с именем шарика движения анимации соответствующие ключевые кадры, соответствующие стилю
  getkeyframes=(name)=> {
    var animation = {};
         // Получить весь стиль
    var ss = document.styleSheets;
    for (var i = 0; i < ss.length; ++i) {
      const item = ss[i];
      if (item.cssRules[0] && item.cssRules[0].name && item.cssRules[0].name === name) {
        animation.cssRule = item.cssRules[0];
        animation.styleSheet = ss[i];
        animation.index = 0;
      }
    }
    return animation;
  }

const ballRunKeyframes = getkeyframes('ball-run');
 // Метод Deleterule используется для удаления указанных правил стиля из объекта текущей таблицы стилей
ballRunKeyframes.styleSheet.deleteRule(animation.index);
 // скидка мяча с положения (20,30) до положения (400 500)
const runkeyframes =` @keyframes ball-run{
    0%{
        left: 20px;
        top: 30px;
    }
    100%{
        left: 400px;
        top: 500px;
    }
}`;
 // Метод вставки используется для внедрения новых правил стиля в текущую таблицу стилей.
ballRunKeyframes.styleSheet.insertRule(keyFrames, animation.index);
 // В настоящее время были изменены ключевые кадры, соответствующие мячом, но в мошенничестве, т. Е. Маленьким и маленьким шариковым шариком, он все еще не изменился на его метод движения. Решение состоит в том, чтобы обновить ценность анимации в шаре DOM от вновь обновить значение анимации в Ball Dom.
const ball = document.getElementById('ball');
 // случайно дано имя анимации
ball.setAttribute('style','animaition: ball-run1 10s infinite;');
setTimeout(_=>{
     // после 1 мс исправьте имя анимации
  ball.setAttribute('style','animaition: ball-run 10s infinite;');
},1)

6. Резюме

  1. Вышеуказанное только предоставляет идеи решения. Рекомендуется не копировать их, потому что код здесь заключается в том, что я написал от руки в книге. Если есть какие -либо вопросы, мы можем оставить сообщение, чтобы обсудить друг друга.
  2. Уведомление:
    1) KeyFrames записывается в стиле отдельно, что удобно для внутреннего пересечения функции GetKeyFrames. Если вы хотите знать, почему, вы можете распечатать ее из структуры. Стильские таблицы, чтобы увидеть структуру внутри.
    2) После того, как JS изменить ключевые кадры, т.е. может не иметь никакого эффекта, и вам нужно пересмотреть значение анимации
  3. Ссылаться наМетод вставки используется для вставки новых правил стиля в текущую таблицу стилей.,Метод Deleterule используется для удаления указанных правил стиля из объекта текущего таблицы стилейДва метода

Автор: Заксизи
Ссылка: https://www.jianshu.com/p/b7b347c9783e
Источник: Цзянь Шу
Авторское право принадлежит автору. Для бизнес -перепечаток, пожалуйста, свяжитесь с автором, чтобы получить авторизацию. Пожалуйста, укажите источник для незащитных перепечаток.

Понравилась статья? Поделить с друзьями:
  • Как изменить jpg на пнг
  • Как изменить jpg на png на андроид
  • Как изменить jpg на pdf на компе
  • Как изменить java home
  • Как изменить iso образ windows 10