Below I will share with you a detailed explanation of a touch event example in mobile web development. It has a good reference value and I hope it will be helpful to everyone.
Previous words
In order to convey some special information to developers, Safari for iOS has added some new exclusive events. Because iOS devices have neither a mouse nor a keyboard, regular mouse and keyboard events are simply not enough when developing interactive web pages for mobile Safari. With the addition of WebKit in Android, many of these proprietary events became de facto standards, leading the W3C to begin developing the Touch Events specification. This article will introduce the mobile touch event in detail
Overview
When the iPhone 3G containing iOS 2.0 software was released, it also included a new version of the Safari browser. This new mobile Safari provides some new events related to touch operations. Later, browsers on Android also implemented the same event. Touch events are triggered when the user places their finger on the screen, slides it across the screen, or moves it away from the screen. Specifically, there are the following touch events
touchstart:当手指触摸屏幕时触发;即使已经有一个手指放在了屏幕上也会触发 touchmove:当手指在屏幕上滑动时连续地触发。在这个事件发生期间,调用preventDefault()可以阻止滚动 touchend:当手指从屏幕上移开时触发 touchcancel:当系统停止跟踪触摸时触发(不常用)。关于此事件的确切触发时间,文档中没有明确说明
[touchenter and touchleave]
The touch event specification once included touchenter and touchleave events. These two events occur when the user's finger moves in or out of a certain area. Triggered when there are elements. But these two events were never realized. Microsoft has alternative events for these two events, but only IE supports them. In some cases, it is very useful to know whether the user's finger slides in and out of an element, so we hope that these two events can return to the specification
In touch events, the commonly used ones are touchstart, touchumove and The three events of touchend correspond to the mouse events as follows
鼠标 触摸 mousedown touchstart mousemove touchmove mouseup touchend
[Note] Some versions of the touch event under the chrome simulator use the DOM0 level event handler to add events that are invalid
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #test{height:200px;width:200px;background:lightblue;} </style> </head> <body> <p id="test"></p> <script> (function(){ var stateMap = { touchstart_index : 0, touchmove_index : 0, touchend_index : 0 }, elesMap = { touch_obj: document.getElementById('test') }, showIndex, handleTouch; showIndex = function ( type ) { elesMap.touch_obj.innerHTML = type + ':' + (++stateMap[type + '_index']); }; handleTouch = function ( event ) { showIndex( event.type ); }; elesMap.touch_obj.addEventListener('touchstart', function(event){handleTouch(event);}); elesMap.touch_obj.addEventListener('touchmove', function(event){handleTouch(event);}); elesMap.touch_obj.addEventListener('touchend', function(event){handleTouch(event);}); })(); </script> </body> </html>
300ms
The 300ms problem refers to a 300 millisecond interval between an element performing its function and executing a touch event. Compared with touch events, mouse events, focus events, browser default behaviors, etc. all have a delay of 300ms
[Click through]
Because of the existence of 300ms, it will cause common click through question. Let’s look at the example first
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #test {position: absolute;top: 0;left: 0;opacity: 0.5;height: 200px;width: 200px;background: lightblue;} </style> </head> <body> <a href="https://baidu.com">百度</a> <p id="test"></p> <script> (function () { var elesMap = { touchObj: document.getElementById('test') }, fnHide, onTouch; fnHide = function (type) { elesMap.touchObj.style.display = 'none'; }; onTouch = function (event) { fnHide(); }; elesMap.touchObj.addEventListener('touchstart', function(event){onTouch(event);}); })(); </script> </body> </html>
After the light blue translucent p is clicked (triggering the touch event), if the click position is just above the link, the default behavior of link jump will be triggered. The detailed explanation is that after clicking on the page, the browser will record the coordinates of the clicked page, and 300ms later, the element will be found at these coordinates. Trigger click behavior on this element. Therefore, if the upper element of the same page coordinate disappears within 300ms, a click behavior will be triggered on the lower element 300ms later. This causes a point-through problem
This problem is caused because the behavior of touching the screen is overloaded. At the moment when the finger touches the screen, the browser cannot predict whether the user is tapping, double-tap, sliding, holding or any other operation. The only safe thing to do is to wait a while and see what happens next
The problem is Double-Tap. Even if the browser detects that the finger has been lifted off the screen, it still has no way of knowing what to do next. Because the browser has no way of knowing whether the finger will return to the screen again, or whether it will end triggering the tap event and event cascade. To determine this, the browser has to wait for a short period of time. Browser developers found an optimal time interval, which is 300 milliseconds
[Solution]
1. Add a 300ms delay in the event handler of the touch event
(function () { var elesMap = { touchObj: document.getElementById('test') }, fnHide, onTouch; fnHide = function (type) { elesMap.touchObj.style.display = 'none'; }; onTouch = function (event) { setTimeout(function(){ fnHide(); },300); }; elesMap.touchObj.addEventListener('touchstart', function (event) { onTouch(event); }); })();
2. Use easing animation and add a 300ms transition effect. Note that the display attribute cannot use transition
3. Add the dom element of the middle layer to let the middle layer accept the penetration event and hide it later
4. Both the upper and lower levels use tap events, but the default behavior is inevitable
5. The touchstart event on the document prevents the default behavior.
document.addEventListener('touchstart',function(e){ e.preventDefault(); })
Next, add the jump behavior of the a tag
a.addEventListener('touchstart',function(){ window.location.href = 'https://cnblogs.com'; })
However, this method has side effects, which will cause the page to be unable to scroll, the text to be unable to be selected, etc. If you need to restore the text selection behavior on an element, you can use prevent bubbling to restore
el.addEventListener('touchstart',function(e){ e.stopPropagation(); })
Event object
【 Basic information】
The event object of each touch event provides common attributes in mouse events, including event type, event target object, event bubbling, event flow, default behavior, etc.
Take touchstart as an example, the sample code is as follows
<script> (function () { var elesMap = { touchObj: document.getElementById('test') }, onTouch; onTouch = function (e) { console.log(e) }; elesMap.touchObj.addEventListener('touchstart', function (event) { onTouch(event); }); })(); </script>
1. The currentTarget attribute returns the node bound to the listening function being executed by the event
2. The target attribute returns the actual target node of the event
3. The srcElement attribute has the same function as the target attribute.
//当前目标 currentTarget:[object HTMLpElement] //实际目标 target:[object HTMLpElement] //实际目标 srcElement:[object HTMLpElement]
4. The eventPhase attribute returns an integer value, indicating the event flow stage in which the event is currently located. 0 means the event did not occur, 1 means the capture stage, 2 means the target stage, 3 means the bubbling stage
5. The bubbles attribute returns a Boolean value, indicating whether the current event will bubble. This property is a read-only property
6. The cancelable property returns a Boolean value indicating whether the event can be canceled. This attribute is a read-only attribute
//事件流 eventPhase: 2 //可冒泡 bubbles: true //默认事件可取消 cancelable: true
[touchList]
除了常见的DOM属性外,触摸事件对象有一个touchList数组属性,其中包含了每个触摸点的信息。如果用户使用四个手指触摸屏幕,这个数组就会有四个元素。一共有三个这样的数组
1、touches:当前触摸屏幕的触摸点数组(至少有一个触摸在事件目标元素上)
2、changedTouches :导致触摸事件被触发的触摸点数组
3、targetTouches:事件目标元素上的触摸点数组
如果用户最后一个手指离开屏幕触发touchend事件,这最后一个触摸点信息不会出现在targetTouches和touches数组中,但是会出现在changedTouched数组中。因为是它的离开触发了touchend事件,所以changedTouches数组中仍然包含它。上面三个数组中,最常用的是changedTouches数组
(function () { var elesMap = { touchObj: document.getElementById('test') }, onTouch; onTouch = function (e) { elesMap.touchObj.innerHTML = 'touches:' + e.touches.length + '<br>changedTouches:' + e.changedTouches.length + '<br>targetTouches:' + e.targetTouches.length; }; elesMap.touchObj.addEventListener('touchstart', function (event) { onTouch(event); }); })();
【事件坐标】
上面这些触摸点数组中的元素可以像普通数组那样用数字索引。数组中的元素包含了触摸点的有用信息,尤其是坐标信息。每个Touch对象包含下列属性
clientx:触摸目标在视口中的x坐标 clientY:触摸目标在视口中的y坐标 identifier:标识触摸的唯一ID pageX:触摸目标在页面中的x坐标(包含滚动) pageY:触摸目标在页面中的y坐标(包含滚动) screenX:触摸目标在屏幕中的x坐标 screenY:触摸目标在屏幕中的y坐标 target:触摸的DOM节点目标
changedTouches数组中的第一个元素就是导致事件触发的那个触摸点对象(通常这个触摸点数组不包含其他对象)。这个触摸点对象含有clientX/Y和pageX/Y坐标信息。除此之外还有screenX/Y和x/y,这些坐标在浏览器间不太一致,不建议使用
clientX/Y和pageX/Y的区别在于前者相对于视觉视口的左上角,后者相对于布局视口的左上角。布局视口是可以滚动的
(function () { var elesMap = { touchObj: document.getElementById('test') }, onTouch; onTouch = function (e) { var touch = e.changedTouches[0]; elesMap.touchObj.innerHTML = 'clientX:' + touch.clientX + '<br>clientY:' + touch.clientY + '<br>pageX:' + touch.pageX + '<br>pageY:' + touch.pageY + '<br>screenX:' + touch.screenX + '<br>screenY:' + touch.screenY }; elesMap.touchObj.addEventListener('touchstart', function (event) { onTouch(event); }); })();
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在angularjs中使用$http实现异步上传Excel文件方法
The above is the detailed content of Touch events in mobile web development (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

appdata文件夹可以移到d盘吗随着电脑使用的日益普及,用户的个人数据和应用程序也越来越多地存储在计算机上。在Windows操作系统中,有一个特定的文件夹,名为appdata文件夹,它用于存储用户的应用程序数据。许多用户想知道是否可以将这个文件夹移到D盘或其他磁盘上,以便进行数据管理和安全性的考虑。在本文中,我们将讨论这个问题并提供一些解决方案。首先,让我

7月23日消息,博主数码闲聊站爆料称,小米15Pro电池容量增大至6000mAh,支持90W有线闪充,这将是小米数字系列电池最大的Pro机型。此前数码闲聊站透露,小米15Pro的电池拥有超高能量密度,硅含量远高于竞品。硅基电池在2023年大规模试水后,第二代硅负极电池被确定为行业未来发展方向,今年将迎来直接竞争的高峰。1.硅的理论克容量可达4200mAh/g,是石墨克容量的10倍以上(石墨的理论克容量372mAh/g)。对于负极而言,当锂离子嵌入量达到最大时的容量为理论克容量,这意味着相同重量下

微软在最新的Windows11版本中将PhoneLink的名称更改为MobileDevice。这一变化使得用户可以通过提示来控制计算机访问移动设备的权限。本文将介绍如何在您的电脑上管理允许或拒绝移动设备访问的设置。该功能让您能够配置移动设备并与计算机连接,从而进行文本消息的发送和接收、移动应用程序的控制、联系人的查看、电话的拨打、图库的查看等操作。将手机连接到PC上是个好主意吗?将手机连接到WindowsPC是一个方便的选择,可以轻松地传输功能和媒体。这对那些需要在移动设备无法使用时使用电脑的人

移动全球通卡分为四个等级,等级从高至低为钻石卡、白金卡、金卡和银卡四级,按照客户不同的等级进行权益匹配,钻石卡的级别最高,级别越高享受的服务越多。一般情况下,系统会在每年1月15日自动根据客户在过去一年的消费和在网网龄综合判断客户的全球通等级,钻卡客户得分需要大于4000分。

移动用户星级一共分为1星、2星、3星、4星、5星五个等级,其中的五星具体又细分为五星金、五星银以及五星钻;星级越高,可享受的服务权益越多。星级每年评定一次,有效期一年;如星级调整,在星级服务将同步调整。

151开头的是移动运营商的号段。151是中国移动号段之一,是移动于2008年开始放号的,也是继158、159、150号段之后发放的第四个非“13”开头的号码区段;151号段启用的目的是为了缓解号码资源紧张。

移动的服务密码是客户的身份识别密码,由一组6位阿拉伯数字组成,可凭服务密码进行相关业务的办理及授权。服务密码由客户在入网时进行设置,如客户未设置将由系统自动生成;如果你不知道的你服务密码,可以编辑短信“MMCZ空格证件号码空格新密码空格新密码“发送至10086,即可重置本机号码的客服密码。

移动184开头是虚拟运营商专属中国移动号段;手机号码段的前三位一般是代表网络识别号,4至7位代表地区编码,8至11位才是用户唯一的号码;在分配号段时,10开头的为电信行业服务号码,比如10000电信服务中心、10010联通服务中心、10086移动服务中心;11开头的为特种服务号码,如110、119等。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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

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.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
