Use native JS to encapsulate the Tap event to solve Ms latency on mobile terminals
FastClick
The existing plug-in fastclick can solve this problem, but it also has drawbacks:
The latest version of the plug-in on GitHub is 25.4kb in size, lightweight as the trend, saving time.
Its core idea is to cancel the default click Time and determine the type of the current dom node for corresponding operations. This judgment process is cumbersome.
MyTapEvent
I am working on a project recently. Due to the disadvantages of the fastclick plug-in, I have developed a simple tap event. The main ideas are as follows:
Thinking
A tap event contains three statuses: touchstart, touchmove (slight movement), and touchend.
The callback method is executed after touchend.
The number of clicks to be canceled is determined based on chrome's default judgment. If the finger offset (horizontal or vertical) exceeds 15 PX, the operation is regarded as rolling and the tap event is canceled.
When the finger is pressed for too long, it is not considered as a click. The default time interval is 500 ms.
Use HTMLElement to expand the prototype to facilitate Event Addition
Use Singleton mode to ensure that only one load is allowed
OK, the idea is fixed, and the code is much clearer:
If (! HTMLElement. prototype. addTapEvent) {HTMLElement. prototype. addTapEvent = function (callback) {var tapStartTime = 0, tapEndTime = 0, tapTime = 500, // tap wait time. In this event, release the trigger method tapStartClientX = 0, tapStartClientY = 0, tapEndClientX = 0, tapEndClientY = 0, tapScollHeight = 15, // If the horizontal or vertical movement exceeds 15 PX, it is determined to be canceled (the number of clicks removed by chrome is determined by default). cancleClick = false; this. addEventListener ('touchstart', function () {tapStartTi Me = event. timeStamp; var touch = event. changedTouches [0]; tapStartClientX = touch. clientX; tapStartClientY = touch. clientY; cancleClick = false;}) this. addEventListener ('touchmove ', function () {var touch = event. changedTouches [0]; tapEndClientX = touch. clientX; tapEndClientY = touch. clientY; if (Math. abs (tapEndClientX-tapStartClientX)> tapScollHeight) | (Math. abs (tapEndClientY-tapStartCl IentY)> tapScollHeight) {cancleClick = true ;}}) this. addEventListener ('touchend', function () {tapEndTime = event. timeStamp; if (! CancleClick & (tapEndTime-tapStartTime) <= tapTime) {callback ();}})}}
Usage
HTMLElement. addTapEvent (function () {// do something ...}) for example, document. querySelect ('# test '). addTapEvent (function () {alert ('this is a tap event ');})
Case
Here is a mobile case. It also contains the knowledge of closures. The first 20 items are the tap events and the last 30 items are the click events. You can try the results on your mobile phone, let's take a look at the differences between the two methods:
Test