flip官网
先看用flip实现的动画效果
它实际实现原理是这样的
总共是有三个box的,我先不隐藏box2,来看看效果
我还从中截了个图
当我点击按钮时,box2就已经在最后位置上了,而box3过渡到box2与其重合。你可以再回头看一下第一张动图,其实我是把box2给变透明了,等到box3与其重合时,box3消失,box2变回原来的样子,这就是flip思想了
flip是first、last、invert、play的首字母缩写
flip思想主要有4个步骤,我结合上面的例子一起讲
1.First:先获取box2的起始位置,然后应用到box3上面,那么box3和box2的起始位置一致
2.Last :再获取box2的最后位置,也就是box2的结束位置
3.Invert :计算出box2最后位置和起始位置的差异,那么我们就知道了box3该移动多少px才能和box2重合了
4.Play —— 添加transtion 过渡效果,播放动画
就是这么简单
vue的过渡与动画中的列表过渡,也就是.v-move css类就是基于此思想来进行平滑过渡的
flip例子完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
span {
width: 100px;
height: 100px;
display: inline-block;
background-color: aqua;
}
.box1{
background-color: burlywood;
}
#but {
position: fixed;
left: 350px;
}
</style>
</head>
<body id="container">
<span class="box1"></span>
<span class="box2"></span>
<button id="but">点击下滑</button>
<script>
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
var ok=0;
but.onclick = function () {
// 让点击按钮只能点击一次
if(ok==1){
return
}
ok++
// 克隆box3
var box3 = box2.cloneNode();
box3.style.position = "absolute";
// 获取box2的起始位置
let first = box2.getBoundingClientRect();
// 将box2的起始位置应用在box3身上
box3.style.top = `${first.y}px`;
box3.style.left = `${first.x}px`;
// 插入box3
container.appendChild(box3);
// box2设置为透明
box2.style.opacity ="0"
// 为了拿到box2的最后位置,绝对定位box1
box1.style.position = "absolute";
// 获取到box2的最后位置
let last = box2.getBoundingClientRect();
// 计算起始位置和最后位置的差异,也就是flip的核心
let invert = {
x: last.x - first.x,
y: last.y - first.y,
};
// 播放动画
box1.style.transform = "translateY(200px)";
box1.style.transition="all 2s"
box3.style.transform = `translateY(${invert.y}px)`;
box3.style.transform = `translateX(${invert.x}px)`;
box3.style.transition="all 2s"
// 过渡结束之后让box3消失,box2变回原样
setTimeout(() => {
box2.style.opacity =""
box3.remove()
},2000);
}
</script>
</body>
</html>