• Background: to make a mobile adaptation of the page, collect a bunch of data found native JS unexpectedly have Touch events !!!! There are touch objects and things like that, but there is no long press event, so you have to “create” it.

Touch Event Introduction

Let’s start with the four basic Touch events

  • Touchstart: touch trigger (finger press)
  • Touchmove: Touch sliding trigger (finger movement)
  • Touchend: triggered when the touch leaves the screen (finger lifted)
  • Touchcancel: Triggered when a touch point is interrupted (used rarely, for example, when creating too many touchpoints can cause an interruption)

To achieve long press

  • Idea: Using timer, when touching until the specified time and no other action occurs, it will be regarded as long press, so there will be processing to judge whether to move or click (specific operation is realized by combining the first three events).
TouchLong () {let timeOutEvent = 0 // Set the timer. Dom.addeventlistener (' touchStart ', TimeOutEvent = setTimeout(function() {timeOutEvent = 0) {function() {timeOutEvent = 0 Console. log(' you long pressed ')}, 1000) // Long press effect will be implemented after 1s}) dom.adDeventListener (' touchMove ', function(e) {// If touch does not reach 1s and start to move, ClearTimeout (timeOutEvent) timeOutEvent = 0}) dom.addeventListener ('touchend', Function (e) {// Clear timer clearTimeout(timeOutEvent) if (timeOutEvent! == 0) {// Check if console.log(' you are clicking, not pressing ')} return false})}Copy the code

What does it mean when timeOutEvent is clearTimeout and then assigned?

ClearTimeout clears the timer. What is the value of timeOutEvent after clearing the timer? , below we look at a picture to figure out!!

  • Explain it. First of alltimer1The timer is timed for 1s, and after 1s the console prints 1, at this pointtimer1The value of the timer is 72, and then another timer is writtentimer2Also timed 1s, but executed at the same timeclearTimeoutStatement, nothing is displayed after 1s, continue printingtimer2The value is 167
  • So,clearTimeoutYou just clear the timer without changing the value of the identifier, so you typically either remove the identifier (timer1/2Etc.), or reassign for later use

If you feel that there is a harvest can be a thumbs up oh!