search
HomeWeb Front-endJS TutorialTouch event usage in JS mobile terminal

Touch event usage in JS mobile terminal

May 21, 2020 am 09:42 AM
jstouch

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. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment