美文网首页
css抛物线动画

css抛物线动画

作者: sweetBoy_9126 | 来源:发表于2020-09-01 11:43 被阅读0次
    1. 我们需要两个容器,一个是内层用来控制垂直方向的移动,一个是外层用来控制水平方向的移动,垂直我们需要用到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>
    
    1. 将我们需要进行抛物线动画的元素的外层设置为固定定位
    .box-wrapper {
      width: 0.6rem;
      height: 0.6rem;
      position: fixed;
      z-index: 1000;
    }
    
    1. 通过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>
    
    1. 不管是外层还是内层都要设置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>
    
    1. 设置我们的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)
    }
    }
    

    相关文章

      网友评论

          本文标题:css抛物线动画

          本文链接:https://www.haomeiwen.com/subject/fotvsktx.html