Home >Web Front-end >JS Tutorial >Touch event usage in JS mobile terminal

Touch event usage in JS mobile terminal

Guanhui
Guanhuiforward
2020-05-21 09:42:312848browse

Touch event usage in JS mobile terminal

With the popularity of smartphones and tablets, more and more people use mobile devices to browse the web. We usually use mouse events on PC browsers, such as: click, mouseover, etc., can no longer meet the characteristics of the touch screen of mobile devices. The arrival of the touch era cannot be separated from those touch events.

Touch event contains 4 interfaces.

TouchEvent

represents an event that occurs when the touch behavior changes on the surface.

Touch

represents a contact between the user's finger and the touch surface Point.

TouchList

represents a series of Touch; This interface is generally used when the user has multiple fingers touching the touch surface at the same time.

DocumentTouch

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

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

TouchEvent interface can respond to basic touch events (such as a single finger click), it contains some specific events,

Event type:

touchstart : Touch start (finger placed on the touch screen)

touchmove : Drag (finger moved on the touch screen)

touchend : Touch end (finger removed from the touch screen)

touchenter: Move the finger into a DOM element.

touchleave: The moving finger leaves a DOM element.

There is also touchcancel, which is triggered when dragging is interrupted.

Event properties:

altKey: This property 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: currently on the screen A list of all finger touch points on the .

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 both 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 event location to the screen, clientX/clienYt and pageX/pageY both represent the offset of the object corresponding to the event location, but the difference is that clientX/clientY does not include the object The offset is hidden when scrolling, and pageX/pageY includes the offset when the object is scrolled and hidden. The touch point that moves the screen will only be included in the changedTouches list, not the touches and targetTouches lists, so changedTouches will be more commonly used in projects.

Example:

<body onload="start();">
<style type="text/css">
#dom {
  width:500px;
  height:500px;
  background:black;
}
</style>
<div id="dom"></div>
<script type="text/javascript">
function onTouchStart(e){
    console.log(e);
}
function start(){
    var dom = document.getElementById(&#39;dom&#39;);
    dom.addEventListener(&#39;touchstart&#39;, onTouchStart, false);
}
</script>
</body>

The console output is as follows:

Touch event usage in JS mobile terminal

The order in which touch events and mouse events are triggered :

Touchstart > toucheend > mousemove > mousedown > mouseup > click

In many cases, touch events and mouse events will be triggered at the same time (the purpose is to prevent touch devices from being optimized The code will still work fine on touch devices), if touch events are used, you can call event.preventDefault() to prevent mouse events from being triggered. However, when the finger moves touchmove on the screen, the mouse event and click event will not be triggered. Adding preventDefault to the touchmove event can prohibit the browser from scrolling the screen and will not affect the triggering of the click event.

Touch event usage in JS mobile terminal

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

Hammer.js is a lightweight JavaScript library that allows your website to easily implement touch events. It relies on jQuery and is used to control multi-touch on touch devices. control characteristics.

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

##The implementation of multi-touch, if you want to know more, please refer to:

http://www.cnblogs.com/iamlilinfeng/p/4239957.htm

zepto is lightweight A library compatible with juqery and suitable for mobile development. For specific usage methods, please refer to the official website.

http://zeptojs.com/

zepto touch is used A touch event module triggered by a single-point gesture.

Touch.js download address:

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

Let’s first look at zepto’s touch module implementation:

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

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

 手机上也有click事件,从触摸到响应click事件,有会300的毫秒的延迟,原因在于:

"Apple 准备发布iphone的时候,为了解决手机上web页面太小的问题,增加了双击屏幕放大的功能,(double tap to zoom ),当用户触摸屏幕的时候,浏览器不知道用户是要double tap还是要click,所以浏览器在第一次tap事件后会等300ms来判断到底是double tap还是click ,如果在300ms以内点击的话,会以为是double tap,反之是click。"

去掉click事件 300ms 的方法:

(1)  在meta里,加 user-scalable=no 可以阻止双击放大,(缺点: 部分浏览器支持)

(2)  使用fastclick.js  它利用多touchstart touchmove 等原生事件的封装,来实现手机上的各种手势,比如tap, swipe 等, 

下载地址 https://github.com/ftlabs/fastclick  

调用很简单:

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

缺点: 文件量有点大,为了解决一小延迟的问题,有点得不偿失。

 

 

自定义事件

 // 创建事件对象
  var obj = new Event(&#39;sina&#39;);
  var elem = document.getElementById(&#39;dom&#39;);
  //监听sina事件
  elem.addEventListener(&#39;sina&#39;, function(e){
    console.log(e);
  },false);
  //分发sina事件
  elem.dispatchEvent(obj);

另外一个创建事件对象的方法是通过CustomEvent,相比于Event的好处是,它可以给处理事件的函数,自定义detail值,这在实际开发中,可能会经常用到。

  // 创建事件对象
  var obj = new window.CustomEvent(&#39;sina&#39;, {
      detail: {&#39;name&#39;: &#39;lily&#39;}
  });
  var elem = document.getElementById(&#39;dom&#39;);
  //监听sina事件
  elem.addEventListener(&#39;sina&#39;, function(e){
    // 可以接收到创建事件时,传入的detail值。
    console.log(e. detail);  // {&#39;name&#39;: &#39;lily&#39;}
  },false);
  //分发sina事件
  elem.dispatchEvent(obj);

 

创建自定义事件,一个兼容性较好的函数:

Touch event usage in JS mobile terminal

 

 

zepto tap “点透”问题

Zepto 的tap事件是通过document绑定了touchstart和touchend事件实现,如果绑定tap方法的dom元素在tap方法触发后会隐藏、而“隐藏后,它底下同一位置正好有一个dom元素绑定了click的事件, 而clic事件有300ms延迟,触发click事件。则会出现“点透”现象。 

解决方案:

1 fastclick.js

它的实际原理是在目标元素上绑定touchstart ,touchend事件,然后在touchend这个库直接在touchend的时候就触发了dom上的click事件而替换了本来的触发时间,touch事件是绑定到了具体dom而不是document上,所以e.preventDefault是有效的,可以阻止冒泡,也可以阻止浏览器默认事件。

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

2、利用fastclick的事件原理, 直接写一段, 采用 e.preventDefault();  阻止“默认行为”,将事件绑定到dom元素上,缺点在于不能使用事件代理。

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

3.  在事件捕获阶段,如果时间差,位置差,均小于指定的值,就阻止冒泡和默认click事件的触发。

Touch event usage in JS mobile terminal

4. 用户点击的时候“弹出”一个顶层DIV,屏蔽掉所有事件传递,然后定时自动隐藏, 这个方法比较巧妙。

推荐教程:《PHP教程

The above is the detailed content of Touch event usage in JS mobile terminal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete