likes
comments
collection
share

Vue之实现加入购物车的过渡效果

作者站长头像
站长
· 阅读数 8

模板代码

这个是vue项目的一部分,这里的图标库来源于cube-ui

<i @click="toCart($event)" class="cubeic-add"></i>
...
<!-- 加入购物车动画(小球) -->
<div class="ball-box">
  <transition @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter">
    <div class="ball" v-if="ball.show">
      <div class="inner">
        <i class="cubeic-add"></i>
      </div>
    </div>
  </transition>
</div>

data数据

ball: {
  show: false, //是否显示小球
  el: "" //获取小球的dom
},

methods方法

// 添加到购物车
toCart(event) {
  // 显示小球
  this.ball.show = true;
  // 获取点击元素
  this.ball.el = event.target;
}
//小球动画
beforeEnter(el) {
  // 让小球移动到点击的位置,获取点击位置
  let dom = this.ball.el;
  let rect = dom.getBoundingClientRect(); // 获取点击dom位置
  let x = rect.left - innerWidth * 0.62;
  let y = -(innerHeight - rect.top);
  el.style.display = "block";
  el.style.transform = `translate3d(0,${y}px,0)`;
  let inner = el.querySelector(".inner");
  inner.style.transform = `translate3d(${x}px,0,0)`;
},
enter(el, done) {
  // 触发重绘
  document.body.offsetHeight;
  // 小球回家
  el.style.transform = `translate3d(0,0,0)`;
  let inner = el.querySelector(".inner");
  inner.style.transform = `translate3d(0,0,0)`;
  // 过渡完成后执行的事件
  el.addEventListener("transitionend", done);
},
afterEnter(el) {
  // 隐藏小球
  this.ball.show = false;
  el.style.display = "none";
},

css代码(注意格式)

// 小球动画
.ball-box {
  .ball {
    position: fixed;
    bottom: 0;
    left: 62%;
    z-index: 2;
    color: #f00;
    transition: all 1s cubic-bezier(0.49, -0.29, 0.75, 0.41);

    .inner {
      transition: all 1s linear;
    }
  }
}

效果演示