Modify the @keyframe value of CSS animation in vue

Sometimes, we need to change the time period animation-duration in animation and the value of transform in keyframe as the click event starts on the page or as time increases.

Method 1 : Add the following code to the relevant method

let style = document.createElement('style');
style.setAttribute('type', 'text/css');
document.head.appendChild(style);
let sheet = style.sheet;
sheet.insertRule('@keyframes shake{0%,100%{ transform: translateY(-'+ this.shakeTranslateY+'vw); }50%{ transform: translateY('+ this.shakeTranslateY+'vw); }}')

Modify the value you want to change using the sheet.insertRule method.

Shake is the name of the animation I defined. At this time, I need to increase the value of shakeTranslateY as the click event occurs repeatedly, so as to increase the distance the animation moves up and down.

Method 2 : Change the value you want to change through the calculated attribute

Step 1: Bind a method in the html element     

<div class="rocket-img" :style="lotteryImg"></div>

2: Declare this method in the calculated attribute

lotteryImg(){
  const style = {};
  style.animationDuration = this.animationImgDuration + "ms";
  return style;
},

3: Change the value of this.animationImgDuration at the logical processing location you need

if( this.animationImgDuration > 100){this.animationImgDuration -= 40}

Optimization: You may find that the animation you make at this time is not coherent and seems to be stuck.

let cloudTimer = setInterval(() => {
  this.animationCloudDuration -= 5 * this.speedNum
  if(this.animationCloudDuration < 30){
    this.animationCloudDuration += 5 * this.speedNum
    this.animationCloudDuration = 30
    clearInterval(cloudTimer)
  }
}, 16)

You can set a timer, the general principle is to simulate the screen refresh frequency.

You can also use requestAnimation directly. Please click to jump to the tutorial. (Others wrote it, I don’t know how to do it)

Guess you like

Origin blog.csdn.net/qq_56715703/article/details/132733945