uniapp/微信小程序实现加入购物车点击添加飞到购物车动画

1、预期效果

2、实现思路

每次点击添加按钮时,往该按钮上方添加一个悬浮元素,通过位移动画将元素移到目标位置。

  1. 为每个点击元素设置不同的class,才能通过uni.createSelectorQuery来获取每个元素的节点信息;

  2. 添加一个与点击元素一模一样的动画元素;

  3. 获取点击元素的节点信息将动画元素放置到点击元素上方;

  4. 计算动画元素到目标位置的距离,获得xy坐标执行位移动画;

  5. 等待每个动画元素执行动画完毕后移除该元素。

3、核心代码

TypeScript 复制代码
<template>
  <view>
    <!-- 商品列表 -->
    <view v-for="item in goodsList" :key="item.id">
      <view :class="[`add-cart-${item.id}`]" @click="addToCart(item)">加购</view>
    </view>
    <!-- 动画元素列表 -->
    <view
      v-for="item in anims" :key="item.key"
      style="position: fixed; transition: transform 0.5s linear;"
      :style="{
        top: `${item.top}px`,
        left: `${item.left}px`,
        transform: `translate(${item.x}px, ${item.y}px)`,
      }"
    >
      加购
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import uniqueId from 'lodash-es/uniqueId';

const sys = uni.getSystemInfoSync();
const anims = ref<any[]>([]);
const goodsList = ref([{ id: 1 }, { id: 2 }, { id: 3 }])

function addToCart(item) {
  // 添加动画元素
  const key = uniqueId();
  anims.value.push({
    key,
    id: item.id,
    left: 0,
    top: 0,
    y: 0,
    x: 0,
  });
  // 获取点击元素的节点信息
  uni.createSelectorQuery().select(`.add-cart-${item.id}`)
    .boundingClientRect((e: any) => {
      // 初始化起始位置
      anims.value.some((citem) => {
        if (citem.key === key) {
          citem.top = e.top;
          citem.left = e.left;
          return true;
        }
        return false;
      });
      nextTick(() => {
        // 设置目标位置
        anims.value.some((citem) => {
          if (citem.key === key) {
            citem.y = sys.windowHeight - citem.top - 50;
            citem.x = -sys.windowWidth * 0.30;
            setTimeout(() => { // 等待动画执行完毕移除元素
              anims.value.splice(anims.value.findIndex((v: any) => v.key === key), 1);
            }, 500);
            return true;
          }
          return false;
        });
      });
    }).exec();
}

</script>
相关推荐
张就是我10659216 小时前
SPIP 的一个漏洞:你以为过滤了,其实没过滤干净
前端
一tiao咸鱼16 小时前
我用 Claude 做了一个 AI 面试刷题系统,支持 DeepSeek / 阿里 / GPT 帮你打分
前端
掘金一周17 小时前
对车完全小白,不知买油买电还是买混动,求建议| 沸点周刊 7.2
前端·人工智能·后端
妙码生花17 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十六):目录结构更新、完善 token 系统(AI 表示 token 入库无需加密?)
前端·后端·ai编程
程序me17 小时前
Prompt、Context、Harness、Loop 之后是什么? AI工程下一个半年的关键词
前端·后端·ai编程
飞天狗17 小时前
线上Bug一直复现不了?我用Sentry把错误追踪效率提升了10倍
前端
Slice_cy17 小时前
对前端工程化的理解
前端
Slice_cy17 小时前
状态机设计理念与实现
前端
星栈17 小时前
LiveView 的生命周期:mount、handle_event 和 Socket 到底怎么运转
前端·前端框架·elixir
yingyima17 小时前
JWT Token 解析与安全实践速查:5 问 5 答直击要害
前端