微信小程序监听页面滑动手势

功能背景是类似小红书顶部Tab,页面中左右滑动时,顶部Tab自动切换。

页面结构:

wxml 复制代码
<Tab  id="tabComponent" />
<scroll-view bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd">

</scroll-view>

主要思路就是:记录滑动位置,滑动结束调用子组件方法,设置当前选中Tab以及后续数据请求操作。

selectComponent直接根据id找到子组件,然后直接调用子组件中提供的setActiveTab方法。

代码实现:

js 复制代码
    // 监听页面滑动手势开始
    touchStartX:0,//记录滑动开始位置
    touchEndX:0,//记录滑动结束位置
    touchStart(e){
        const x = e.touches[0].pageX;
        // console.log('滑动开始',x);
        this.touchStartX = x;
    },
    touchMove(e){
        const x = e.touches[0].pageX;
        // console.log('滑动中',x);
        this.touchEndX = x;
    },
    touchEnd(e){
        // console.log('滑动结束',e)
        const {touchStartX,touchEndX} = this;
        const tabComponent = this.selectComponent('#tabComponent');
        if(touchStartX < touchEndX - 50){
            // 向右滑动了
            tabComponent.setActiveTab(-1);
        }
        if(touchStartX > touchEndX + 50){
            // 向左滑动了
            tabComponent.setActiveTab(1);
        }
    },
    // 监听页面滑动手势结束
    
相关推荐
To_OC5 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮5 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny5 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹6 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny6 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC6 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn6 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker7 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜7 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康7 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端