1024programmer JavaScript Use of Touch events on JS mobile terminals

Use of Touch events on JS mobile terminals

With the popularization of smart phones and tablet computers, more and more people use mobile devices to browse the web. The mouse events we usually use on PC browsers, such as: click, mouseover, etc., are no longer available Satisfying the characteristics of the touch screen of mobile devices, the arrival of the touch era is inseparable from those touch events.

Touch event contains 4 interfaces.

TouchEvent

Represents the event that occurs when the touch behavior changes on the plane.

Touch

Represents the user’s finger and the touch plane A touch point between.

TouchList

Represents a series of Touch; Generally, this interface is used when the user touches the touch surface with multiple fingers at the same time.

DocumentTouch

contains some convenient methods for creating Touch objects and TouchList objects.

(refer to https:/ /developer.mozilla.org/zh-CN/docs/Web/API/Touch_events )

The TouchEvent interface can respond to basic touch events (such as a single finger click), which contains Some specific events,

Event type:

touchstart: touch start (finger on the touch screen)

touchmove: drag (finger on the touch screen Move)

touchend: The touch ends (the finger is removed from the touch screen)

touchenter: The moving finger enters a dom element.

touchleave: The moving finger leaves a dom element.

There is also a touchcancel, which is triggered when the drag is interrupted.

Event attribute:

altKey : This attribute returns a Boolean value indicating whether the Alt key is pressed when the specified event occurs, event.altKey=true|false| 1|0

type : The type of event triggered when touching, such as touchstart

Each touch event includes three touch attribute lists:

1. touches: A list of all finger touches currently on the screen.

2. targetTouches: A list of all touch points on the current element object.

3. changedTouches: A list of touch points involved in the current event.

They are all an array, each element represents a touch point.

The Touch corresponding to each touch point has three pairs of important attributes, clientX/clientY, pageX/pageY, screenX/screenY.

Where screenX/screenY represents the offset of the location where the event occurred to the screen, clientX/clienYt and pageX/pageY both represent the offset of the object corresponding to the location where the event occurred, but the difference is that clientX/clientY does not include The offset that the object scrolls and hides, and pageX/pageY includes the offset that the object scrolls and hides. The touch point that moves away from the screen will only be included in the changedTouches list, not in the touches and targetTouches lists, so changedTouches will be more commonly used in projects.

Example:




 

The console output is as follows:

The above events are all built-in in the system and can be used directly. Through these built-in events, many non-native events can be combined Multi-touch gestures touch gestures.

Hammer.js is a lightweight Javascript library that allows your website to easily implement touch events. It relies on jQuery to control multiple touch events on touch devices. Touch features.

Official website: http://hammerjs.github.io/

For the realization of multi-touch, if you want to know more, please refer to: http://www.cnblogs.com/iamlilinfeng/p/4239957.htm

zepto is a lightweight library compatible with juqery, suitable for mobile development, for specific usage, please refer to the official website, http://zeptojs.com/

zepto touch is a touch for single-point gesture triggering event module.

Touch.js download link: https://github.com/madrobby/zepto/blob/master/src/touch.js

First look at the touch module implementation of zepto:

 $(document)
      .on('touchstart ...', function(e){
               ...
              ...
               now = Date. now()
              delta = now - (touch.last || now)
               if (delta > 0 && delta <= 250) touch.isDoubleTap = true
               touch.last = now
      })
      .on('touchmove ...', function(e){
      })
      .on('touchend ...', function(e){
             ...
             if (deltaX <30 && deltaY <30) {
                    var event = $.Event('tap')
                 
                    touch.el.trigger(event)
             }
      })

The touch module binds events touchstart, touchmove, touchend to the document, and then realizes custom tap and swipe events by calculating the time difference and position difference triggered by the event.

There is also a click event on the mobile phone. From touch to response to the click event, there will be a delay of 300 milliseconds. The reason is:

“When Apple is preparing to release the iphone, in order to solve the The web page is too small, and the double tap to zoom function has been added. When the user touches the screen, the browser does not know whether the user wants to double tap or click, so the browser taps for the first time. After the event, it will wait 300ms to determine whether it is a double tap or a click, such as��If you click within 300ms, it will be considered a double tap, otherwise it will be a click. “

How to remove the 300ms click event:

(1) In the meta, add user-scalable=no to prevent double-click zooming, (disadvantage: some browsers support)

p>

(2) Use fastclick.js, which uses multi-touchstart touchmove and other native event packages to realize various gestures on mobile phones, such as tap, swipe, etc.,

Download URL https://github.com/ftlabs/fastclick

The call is simple:

$(function() {
     FastClick. attach(document. body);
 });

Disadvantages: The amount of files is a bit large. In order to solve the problem of a small delay, the gain outweighs the gain.

Custom Event

 // Create event object
   var obj = new Event('sina');
   var elem = document.getElementById('dom');
   //Listen to sina events
   elem.addEventListener('sina', function(e){
     console. log(e);
   }, false);
   //Distribute sina events
   elem.dispatchEvent(obj);

Another way to create an event object is through CustomEvent. Compared with Event, the advantage is that it can customize the detail value for the function that handles the event, which is in actual development , may be frequently used.

 // create event object
   var obj = new window. CustomEvent(& # 39; sina & # 39;, {
       detail: {'name': 'lily'}
   });
   var elem = document.getElementById('dom');
   //Listen to sina events
   elem.addEventListener('sina', function(e){
     // You can receive the detail value passed in when the event was created.
     console.log(e.detail); // {'name': 'lily'}
   }, false);
   //Distribute sina events
   elem.dispatchEvent(obj);

Create a custom event, a function with better compatibility:

zepto tap “click through” problem

Zepto’s tap event is realized by binding the touchstart and touchend events through the document, if the dom element of the tap method is bound After the tap method is triggered, it will be hidden, and after “hiding”, there is a dom element at the same position below it that is bound to a click event, and the clic event has a 300ms delay, triggering the click event. There will be a “click through” phenomenon.

Solution:

1 fastclick.js

Its actual principle is to bind touchstart and touchend events on the target element, and then directly in the touchend library When touchend triggers the click event on the dom and replaces the original trigger time, the touch event is bound to the specific dom instead of the document, so e.preventDefault is effective, it can prevent bubbling, and it can also prevent the browser Default event.

http://www.cnblogs.com/yexiaochai/p/3442220.html

2. Use the event principle of fastclick to write a paragraph directly, using e.preventDefault(); to prevent the “default behavior” and bind the event to the dom element. The disadvantage is that you cannot use event proxy.

elem.addEventListener(touchend, function(e){
 e.preventDefault()
 },false);

3. In the event capture phase, if the time difference and position difference are less than the specified value, the bubbling and triggering of the default click event will be prevented.

4. When the user clicks, a top-level DIV “pops up”, shields all event transmission, and then automatically hides it at regular intervals. This method is more ingenious.

Recommended tutorial: “PHP Tutorial”

The above is the detailed content of the use of the Touch event on the JS mobile terminal. For more information, please pay attention to other related articles on 1024programmer.com!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/use-of-touch-events-on-js-mobile-terminals/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索