返回

微信小程序实现卡片左右滑动效果——左右滑动,划出新世界

前端

实现卡片左右滑动效果,最优方案是直接使用微信小程序的swiper组件。本文提供另一种思路,有兴趣可以了解一下。

首先,先看效果图。左右滑动到一定的距离,就向相应的方向移动一个卡片的位置。卡片滑动的时候有一定的加速度。

如果滑动距离超过卡片宽度的一半,则卡片移动到下一个位置。否则,卡片移动到上一个位置。

卡片滑动速度与滑动距离成正比,与卡片质量成反比。卡片质量越大,滑动速度越慢。

下面是实现卡片左右滑动效果的代码:

<template>
  <view class="card-container">
    <view class="card" wx:for="{{cards}}" wx:key="index">
      {{item.text}}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cards: [
        { text: '卡片1' },
        { text: '卡片2' },
        { text: '卡片3' },
      ],
      startX: 0, // 手指按下时的x坐标
      startY: 0, // 手指按下时的y坐标
      moveX: 0, // 手指移动时的x坐标
      moveY: 0, // 手指移动时的y坐标
      distanceX: 0, // 手指移动的x轴距离
      distanceY: 0, // 手指移动的y轴距离
      isScrolling: false, // 是否正在滑动
    }
  },
  methods: {
    touchstart(e) {
      this.startX = e.touches[0].clientX
      this.startY = e.touches[0].clientY
    },
    touchmove(e) {
      this.moveX = e.touches[0].clientX
      this.moveY = e.touches[0].clientY
      this.distanceX = this.moveX - this.startX
      this.distanceY = this.moveY - this.startY
      if (Math.abs(this.distanceX) > Math.abs(this.distanceY)) {
        this.isScrolling = true
      }
    },
    touchend(e) {
      if (this.isScrolling) {
        if (this.distanceX > this.cardWidth / 2) {
          this.moveCard('right')
        } else if (this.distanceX < -this.cardWidth / 2) {
          this.moveCard('left')
        }
        this.isScrolling = false
      }
    },
    moveCard(direction) {
      if (direction === 'left') {
        this.cards.unshift(this.cards.pop())
      } else {
        this.cards.push(this.cards.shift())
      }
    },
  },
  computed: {
    cardWidth() {
      return this.$refs.card.getBoundingClientRect().width
    },
  },
}
</script>

<style>
.card-container {
  display: flex;
  flex-direction: row;
}

.card {
  width: 100px;
  height: 100px;
  margin: 0 10px;
  background-color: #ccc;
  text-align: center;
  line-height: 100px;
}
</style>

本文中的代码可以实现卡片左右滑动效果,但并不是最优方案。最优方案是直接使用微信小程序的swiper组件。

感谢您的阅读!