- 我们需要两个容器,一个是内层用来控制垂直方向的移动,一个是外层用来控制水平方向的移动,垂直我们需要用到translateY,水平用到translateX
<div class="box-wrapper" :style="transform: `translateX(${translateX}px)`">
<div class="inner" :style="transform: `translateY(${translateY}px)`"></div>
</div>
<script>
export default {
data() {
return {
translateX: 0,
translateY: 0
}
}
}
</script>
- 将我们需要进行抛物线动画的元素的外层设置为固定定位
.box-wrapper {
width: 0.6rem;
height: 0.6rem;
position: fixed;
z-index: 1000;
}
- 通过js的getBoundingClientRect()来设置当前外层的left和top的初始位置
<div ref="positionRef">动画需要从这里开始</div>
<div class="box-wrapper" :style="transform: `translateX(${translateX}px)`, left: `${coinLeft}px`, top: `${coinTop}px`">
<div class="inner" :style="transform: `translateY(${translateY}px)`"></div>
</div>
<script>
data () {
return {
coinLeft: 0,
coinTop: 0
}
},
method: {
getInitPosition () {
const {left, top} = this.$refs.positionRef.getBoundingClientRect()
this.coinLeft = left
this.coinTop = top
}
}
</script>
- 不管是外层还是内层都要设置
all cubic-bezier(0,.57,.43,.88)
,外层的需要设置为cubic-bezier(0,0,0,0)
,这里内层的值我们可以通过http://cubic-bezier.com这个网站生成
<div class="box-wrapper" :style="transform: `translateX(${translateX}px)`, left: `${coinLeft}px`, top: `${coinTop}px`, transition: `all cubic-bezier(0,0,0,0) ${movetime}s`">
<div class="inner" :style="transform: `translateY(${translateY}px)`, transition: `all cubic-bezier(0,.57,.43,.88) ${movetime}s`"></div>
</div>
- 设置我们的
translateX
为需要到达的位置的left - 初始位置的left,translateY
为需要到达位置的top - 初始位置的top
<div ref="endRef">动画要到达的位置</div>
<div @click="onClickStartAnimation">开始</div>
<script>
const {left, top} = this.$refs.endRef.getBoundingClientRect()
this.translateX = left - this.coinLeft
this.translateY = top - this.coinTop
</script>
完整代码:
data () {
return {
movetime: 0,
coinLeft: 0,
coinTop: 0,
translateX: 0,
translateY: 0
}
},
methods: {
getInitPosition () {
const {left, top} = this.$refs.positionRef.getBoundingClientRect()
this.coinLeft = left
this.coinTop = top
},
onClickStartAnimation () {
this.getInitPosition()
const {left, top} = this.$refs.endRef.getBoundingClientRect()
setTimeout(() => {
this.movetime = 1
this.translateX = left - this.coinLeft
this.translateY = top - this.coinTop
setTimeout(() => {
// 动画结束后的操作
}, 800)
}, 60)
}
}
网友评论