uniapp 向左滑动进入下一题,向右滑动进入上一题功能实现

在 UniApp 中实现向左滑动进入下一题,向右滑动进入上一题的功能,可以利用触摸事件来判断用户的滑动方向。下面是一个简单的实现示例:

  1. 创建基本的项目结构:确保你有一个可以显示的问题的页面。

  2. 监听触摸事件:通过 touchstart 和 touchend 事件来判断用户的滑动方向。

  3. 实现跳转逻辑:根据滑动的方向改变当前问题的索引。

<template>
  <view class="container" @touchstart="touchStart" @touchend="touchEnd">
    <view class="question">
      <text>{{ currentQuestion }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      questions: ["问题 1", "问题 2", "问题 3", "问题 4"], // 题目数组
      currentIndex: 0, // 当前题目的索引
      startX: 0, // 手指开始滑动的位置
      endX: 0 // 手指结束滑动的位置
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex]; // 当前题目
    }
  },
  methods: {
    touchStart(e) {
      this.startX = e.touches[0].clientX; // 记录开始滑动的位置
    },
    touchEnd(e) {
      this.endX = e.changedTouches[0].clientX; // 记录滑动结束的位置
      this.handleSwipe(); // 处理滑动逻辑
    },
    handleSwipe() {
      const distance = this.endX - this.startX; // 计算滑动距离
      const SWIPE_THRESHOLD = 50; // 滑动阈值

      if (distance > SWIPE_THRESHOLD) {
        this.prevQuestion(); // 向右滑动,上一题
      } else if (distance < -SWIPE_THRESHOLD) {
        this.nextQuestion(); // 向左滑动,下一题
      }
    },
    nextQuestion() {
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++; // 增加索引,显示下一题
      }
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--; // 减少索引,显示上一题
      }
    }
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.question {
  font-size: 24px;
}
</style>

 

说明:

  1. 数据结构questions 数组中存储了问题内容,currentIndex 用于跟踪当前显示的问题索引。

  2. 事件处理

    • touchStart 记录手指开始滑动的位置。
    • touchEnd 记录滑动结束的位置,并调用滑动处理逻辑。
  3. 滑动逻辑:根据计算的滑动距离决定是进入下一题还是上一题。定义了一个阈值 SWIPE_THRESHOLD,只有当滑动距离超过这个值时才会触发问题的切换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值