1、基于class
html代码
<!--基于class的动画和过渡-->
<div id="example1">
不可以直接在外框div块进行操作
<p :class="{shake:noActivated}">
<button @click="noActivated = !noActivated">点我一下</button>
<span v-if="noActivated">当点击button按钮的时候,我就出</span>
</p>
</div>
css 代码
#example1,#test1{
.shake {
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
perspective: 1000px;
}
}
@keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}
js代码
Vue.createApp({
data(){
return{
noActivated:false,
}
},
}).mount('#example1')
2、 基于style
html代码
<div id="example2">
<div
@mouseover="move"
:style="style"
class="movearea"
>
<h3>移动你的鼠标就会触发事件</h3>
<p>x:{{x}}</p>
</div>
</div>
css代码
#example2{
.movearea{
transition: 0.2s background-color ease;
}
}
js代码
// 写一个防抖类
class Fd
{
constructor(property)
{
this.property = property;
this.value = undefined;
this.tm = null; //延时函数
}
update(value){
this.value = value;
if (this.tm === null)
{
this.tm = setTimeout(()=>{
this.property.x = this.value;
this.tm = null;
console.log('防抖更新')
},100)
}
}
}
// 基于style
Vue.createApp({
data(){
return{
x:0,
fd:new Fd(this),
width:500,
}
},
methods:{
move(e){
this.fd.update(e.clientX)
}
},
//添加一个计算属性 让颜色改变时更顺滑
computed:{
style(){
return{
width: `${this.width}px`,
height:'200px',
border:'1px solid white',
backgroundColor:`rgb(${this.rgb_r},${255 -this.rgb_r},155)`,
transition:'background-color 0.1s ease-in',
transform:'translateZ(0)'
};
},
rgb_r(){
return Math.round(this.x * (255/this.width));
}
}
}).mount('#example2')
//1、这个鼠标滑过的函数 如果需要写防抖函数的话 2、颜色更新的不算顺滑 添加一个计算属性
硬件加速
诸如 perspective、backface-visibility 和 transform:translateZ(x) 等 property 将让浏览器知道你需要硬件加速。
具体用法为:在css中这样设置,任选一个都可
perspective: 1000px;
backface-visibility: hidden;
transform: translateZ(0);
此外,许多像 GreenSock 这样的 JS 库都会默认你需要硬件加速,并在默认情况下应用,所以你不需要手动设置它们。
缓动效果
缓动效果是在动画中表达深度的一个重要方式。动画新手最常犯的一个错误是在起始动画节点使用 ease-in,在结束动画节点使用 ease-out。实际上你需要的是反过来的。
VUE自带的transition
** 添加过渡的四个情形:**
- v-if
- v-show
- 动态组件
- 组件根节点??
html代码:
<div id="example4">
<button @click="show = !show">点击切换是否显示测试语句</button>
<transition name="my-example4-transition">
<p v-show="show">{{message}}</p>
</transition>
</div>
css代码:
#example4{
//对于v-show 切换是否显示的元素 进行过渡控制
.my-example4-transition-enter-active,.my-example4-transition-leave-active{
transition: opacity 0.5s ease;
}
.my-example4-transition-enter-from,.my-example4-transition-leave-to{
opacity: 0;
}
}
js代码:
Vue.createApp({
data(){
return{
message:'我是测试example4里被transition包裹的一段话,vue内置过渡有六个阶段',
show:true
}
}
}).mount('#example4')
当插入或删除包含在 transition 组件中的元素时,Vue 将会做以下处理(摘自官网):
- 自动嗅探目标元素是否应用了 CSS 过渡或动画,如果是,在恰当的时机添加/删除 CSS 类名。
- 如果过渡组件提供了 [JavaScript 钩子函数],这些钩子函数将在恰当的时机被调用。
- 如果没有找到 JavaScript 钩子并且也没有检测到 CSS 过渡/动画,DOM 操作 (插入/删除) 在下一帧中立即执行。(注意:此处指浏览器逐帧动画机制,和 Vue 的 `nextTick` 概念不同)