当前位置:   article > 正文

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

uniapp 添加购物车动效

1、预期效果 

2、实现思路

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

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

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

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

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

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

3、核心代码

  1. <template>
  2. <view>
  3. <!-- 商品列表 -->
  4. <view v-for="item in goodsList" :key="item.id">
  5. <view :class="[`add-cart-${item.id}`]" @click="addToCart(item)">加购</view>
  6. </view>
  7. <!-- 动画元素列表 -->
  8. <view
  9. v-for="item in anims" :key="item.key"
  10. style="position: fixed; transition: transform 0.5s linear;"
  11. :style="{
  12. top: `${item.top}px`,
  13. left: `${item.left}px`,
  14. transform: `translate(${item.x}px, ${item.y}px)`,
  15. }"
  16. >
  17. 加购
  18. </view>
  19. </view>
  20. </template>
  21. <script setup lang="ts">
  22. import { ref } from 'vue';
  23. import uniqueId from 'lodash-es/uniqueId';
  24. const sys = uni.getSystemInfoSync();
  25. const anims = ref<any[]>([]);
  26. const goodsList = ref([{ id: 1 }, { id: 2 }, { id: 3 }])
  27. function addToCart(item) {
  28. // 添加动画元素
  29. const key = uniqueId();
  30. anims.value.push({
  31. key,
  32. id: item.id,
  33. left: 0,
  34. top: 0,
  35. y: 0,
  36. x: 0,
  37. });
  38. // 获取点击元素的节点信息
  39. uni.createSelectorQuery().select(`.add-cart-${item.id}`)
  40. .boundingClientRect((e: any) => {
  41. // 初始化起始位置
  42. anims.value.some((citem) => {
  43. if (citem.key === key) {
  44. citem.top = e.top;
  45. citem.left = e.left;
  46. return true;
  47. }
  48. return false;
  49. });
  50. nextTick(() => {
  51. // 设置目标位置
  52. anims.value.some((citem) => {
  53. if (citem.key === key) {
  54. citem.y = sys.windowHeight - citem.top - 50;
  55. citem.x = -sys.windowWidth * 0.30;
  56. setTimeout(() => { // 等待动画执行完毕移除元素
  57. anims.value.splice(anims.value.findIndex((v: any) => v.key === key), 1);
  58. }, 500);
  59. return true;
  60. }
  61. return false;
  62. });
  63. });
  64. }).exec();
  65. }
  66. </script>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/654192
推荐阅读
相关标签
  

闽ICP备14008679号