今天想玩玩 css3 动画的时候,在 vue 项目里面写了半天css3,结果都没效果,我还在想,是我老了吗,提不动刀了???!!(一开始还以为是浏览器兼容的问题,加了兼容的代码,换了好几个浏览器都不行。。。别问,问就是我蠢发555~~~)

然后我不信邪的单独建一个 html 页面,将一模一样的css copy 过去,结果明明就可以运行嘛!!!

然后百度了好久,就只百度到 好像跟 scoped 有关 , 加了scoped 就不生效 ( 原因我也不知道昂。。。),一开始我的代码如下,运行无效

<template>
  <div class="home">
    <div class="box1 "></div>
  </div>
</template>

<script>
export default {
  name: "Home",
};
</script>

<style lang="scss" scoped>
.box1 {
  width: 200px;
  height: 200px;
  background: pink;
  animation: drive 5s linear 2s infinite alternate;
}

@keyframes drive {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(700px);
  }
}

// 兼容 chrome 和 Safari
@-webkit-keyframes drive {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(700px);
  }
}
</style>

在这里插入图片描述

然而但是 我不想去掉 scoped,没错就是这么任性,然后我就想到了一个很”实在” 的方法哈哈哈,就是 将 css3 的动画效果,打包放进另一个 css 文件里面,然后 在当前的 vue 文件里面引用进来使用,这样还提高了代码的可复用性,我是不是很机智哈哈哈,完美

在这里插入图片描述
animation.css 内容如下

@keyframes drive {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(700px);
  }
}
@-webkit-keyframes drive {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(700px);
  }
}

然后 在我的 vue 文件里面,引用

<template>
  <div class="home">
    <div class="box1 "></div>
  </div>
</template>

<script>
export default {
  name: "Home",
};
</script>

<style lang="scss" scoped>
@import '../assets/css/animation.css';  // 这里注意不要省略后面的分号
.box1 {
  width: 200px;
  height: 200px;
  background: pink;
  animation: drive 5s linear 2s infinite alternate;
}
</style>


你看你看!! 它动了!!动了!!!啊啊啊!!!

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐