H5移动端模拟长按事件

2020-12-30  本文已影响0人  指尖跳动

这是我做react项目的时候写的,其他框架稍作改动即可。

<button onTouchStart=  {this.handelTouchStart.bind(this)}
             onTouchMove={this.handelTouchMove.bind(this)}
             onTouchEnd={this.handelTouchEnd.bind(this)}>
</button>
    handelTouchStart(e) {
        const { target } = e;
        const { touches: [touch] } = e;
        target.touchX = touch.clientX;
        target.touchY = touch.clientY;
        target.touchT = Date.now();
        target.longTapTick = setTimeout(() => {
            console.log('长按了。。。');
        }, 3000);
    }

    handelTouchMove(e) {
        const { target } = e;
        const { touches: [touch] } = e;
        const   { clientX: x,  clientY: y } = touch;
        if (Math.abs(y - target.touchY) > 10 || Math.abs(x - target.touchX) > 10) {
            clearTimeout(target.longTapTick);
        }
    }

    handelTouchEnd(e) {
        const { target } = e;
        clearTimeout(target.longTapTick);
    }
上一篇 下一篇

猜你喜欢

热点阅读