uniapp左右滑动切换题目

思路

  • 监听触摸事件 touchstart 和 touchend,根据相减的距离的正负判断用户是左滑(上一题)还是右滑(下一题)

实现

页面:设置滑动页面的区域;用 v-for 遍历数据;用 v-if 控制展示隐藏题目;给数据绑定触摸事件

 

<view class="slide-the-answer-container" >
    <!-- 滑动页面区域 -->
    <view 
        class="slide-area" 
        v-for="(item,index) in topic"
        v-if="index==nth || newIndex==index"
        @touchstart="touchStart"
        @touchend="touchEnd($event,index)">
    	<!-- 答题盒子 -->
        <view class="topic-box">
            <view>{{item.title}}</view>
        </view>
    </view>
</view>

data 数据:

startX: 0, // 滑动开始x轴位置
moveX: 0, // 滑动的x轴距离
nth: 0, // 当前第几题(以下标计算)
newIndex: 0, // 滑动到第几题(以下标计算)
topic: [ // 题目
    { title: '第1题' },
    { title: '第2题' },
    { title: '第3题' },
    { title: '第4题' },
    { title: '第5题' },
    { title: '第6题' },
    { title: '第7题' },
    { title: '第8题' },
    { title: '第9题' },
    { title: '第10题' }
]

 

触摸事件:判断用户手势,切换题目

 

touchStart(e) { // 手指触摸屏幕时触发,有一个手指放在屏幕上也会触发
    // 获取触摸时的原点
    this.startX = e.changedTouches[0].pageX // 触摸目标在页面中的X坐标
    console.log('开始触摸:', this.startX);
},
touchEnd(e,index) { // 手指离开屏幕时触发
    // 获取滑动距离
    const moveX = e.changedTouches[0].pageX - this.startX
    // 判断滑动方向
    if (moveX < -100 && index<this.topic.length-1) {
    	// 【下一题】 判断大幅度左滑且不是最后一题
        this.newIndex=this.newIndex+1
        this.nth= this.nth+1
        console.log('第'+this.index+'题');
    }
    else if (moveX > 100 && index!= 0) { 
         // 【上一题】 判断大幅度右滑且不是第一题
         this.newIndex=this.newIndex-1
         this.nth=this.nth-1
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值