react 触摸事件,滑动事件 ontouch

2020-07-29  本文已影响0人  写代码的杰西

div上加上

onTouchStart={this.handleTouchStart}
                onTouchMove={this.handleTouchMove}
                onTouchEnd={this.handleTouchEnd}>

处理事件如下,方法比较简单不做过多描述

/*手接触屏幕*/
    handleTouchStart = (e) => {
        this.startY = e.touches[0].clientY;
    };
    /*手在屏幕上移动*/
    handleTouchMove = (e) => {
        this.endY = e.touches[0].clientY;
    };
    /*手离开屏幕*/
    handleTouchEnd = (e) => {
        // 获取滑动范围
        if(this.startY>-1 && this.endY>-1){
            let distance = Math.abs(this.startY - this.endY);
            if (distance > 50) {
                if (this.startY > this.endY) {
                    let {showIndex} = this.state
                    showIndex ++
                    this.setState({showIndex})
                } else {
                    let {showIndex} = this.state
                    showIndex --
                    this.setState({showIndex})
                }
            }
        }
        
        this.startY=-1
        this.endY=-1
    };
上一篇 下一篇

猜你喜欢

热点阅读