vue中修改css的animation的@keyframe数值

有时候,我们需要在页面随着点击事件的启动,或者是时间的增长,变化animation中的时间周期animation-duration、以及keyframe中transform的值。

方式一:在相关方法中加入以下代码

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); }}')

将你想要改变的数值用sheet.insertRule的方法进行修改。

shake是我定义的动画名字,我此时需要随着点击事件的重复发生,增加shakeTranslateY的值,以此来达到递增动画上下移动的距离。

方法二:通过计算属性computed来改变你想改变的值

步骤1:在html元素中绑定一个方法     

2:在计算属性中声明这个方法

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

3:在你所需要的逻辑处理位置改变this.animationImgDuration的值

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

优化:你可能会发现你此时做的动画并不连贯,好像有些卡顿。

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

可以设置一个定时器,大致原理就是模拟屏幕刷新频率。

也可以直接用requestAnimation。教学请点击跳转。(别人写的,我不会)

你可能感兴趣的:(功能实现,学习笔记,知识点简述,vue.js,css,前端)