touchstart and click at the same time trigger

Causes of conflict

We can simultaneously bind touchstart and click event to an element, but this will lead to solving the problems of this article - these two events conflict on mobile devices.

Because mobile devices can simultaneously identify touchstart and click events, so when the user clicks the target element, binding touchstart events on the target element and click event (after about 300ms) in turn is triggered, that is to say, we are bound the callback function will be executed twice! . This is obviously not the result we want.


solution

(1) native JS

Method One:
preventDefault method uses the event object, the role preventDefault method is: stop element default event behavior occurs, but it is interesting, when we simultaneously bind touchstart and click events in the target element, the event callback function in touchstart using this method, it is possible to prevent the occurrence of a subsequent click event.

const Button = document.getElementById("targetButton")
Button.addEventListener("touchstart", e => {
 e.preventDefault()
 console.log("touchstart event!")
})
 
Button.addEventListener("click", e => {
 e.preventDefault()
 console.log("click event!")
})

Method Two:

Based on the binding event detection function

We can determine whether the browser supports the Click event touchstart event to encapsulate elements, so that the client can determine the type of event elements should be bound according to the current environment, as follows:

const Button = document.getElementById("targetButton")
const clickEvent = (function() {
 if ('ontouchstart' in document.documentElement === true)
 return 'touchstart';
 else
 return 'click';
})();
 
Button.addEventListener(clickEvent, e => {
 console.log("things happened!")
})

(2) VUE solution:

HTML

   <div class="comment-text" 
     @touchstart.prevent="gtouchstart(XXX)"
     @touchend.prevent="triggerReply(XXXX)">
     {{ item.content}}
 </div>
                                

JS

 data: function () {
    return {
          Loop: 0
      };
  }
   gtouchstart: function (XXXX) {
        let self = this;
        //执行长按的内容
        self.Loop = setTimeout(function () {
            self.Loop = 0;
            //XXXXXXXXXXXXXXX
        }, 500);
        return false;
    },
    triggerReply: function (XXXX) {
        let self = this;
        clearTimeout(self.Loop);
        //这里click内容
        if (self.Loop !== 0) {
             //XXXXXXXXXXXXXXX
        }
        return false;
    },

Add touchstart.prevent, organizational click event.


Click on the sequence of events

Click on the event can be decomposed into multiple events

In the mobile terminal, finger click an element, it will go through: touchstart -> touchmove -> touchend -> the Click

Guess you like

Origin blog.csdn.net/qq_24147051/article/details/93617468