Detect left/right-swipe on touch-devices, but allow up/down-scrolling

前端 未结 5 1461
逝去的感伤
逝去的感伤 2020-12-04 11:24

I need to detect and react to left/right-swipes, but want to give the user the ability to scroll on the same element, so as long as he moves his finger only left/right with

5条回答
  •  遥遥无期
    2020-12-04 11:56

    All of these codes need improvement (like most of the codes that you can find on touch manipulation).

    When playing with touch event, keep in mind that user have more than one finger, that a touch has an identifier and that touches list represent all current touches on the surface, even touches that have not moved.

    So the process is relatively simple:

    1. ontouchstart: get the first changed touch (not event.originalEvent.touches property, but event.originalEvent.changedTouches one). Register its identifier with event.originalEvent.changedTouches[0].identifier and touch properties to look for (pageX/pageY or clientX/clientY that are pretty usefull in combination with DOMElement.getBoundingClientRect() method);

    2. ontouchmove: make sure that the current touch is in the changedTouches list with event.originalEvent.changedTouches.identifiedTouch( identifier ). If it return nothing, that means that the user has moved another touch (not the one you are looking for). Also register touch properties to look for and do whatever you want with.

    3. ontouchend: again, you must be sure the current touch is in changedTouches list. Do the job with touch properties and finally discard your current touch identifier.

    If you want to do it stronger, consider multiple touches (not only one) to observe.

    More information about TouchEvent, TouchList and Touch on: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Touch_events

提交回复
热议问题