search
HomeWeb Front-endHTML TutorialDetailed explanation of touch event examples in web development
Detailed explanation of touch event examples in web developmentJan 17, 2018 pm 04:57 PM
touchwebDetailed explanation

This article mainly shares with you a detailed explanation of touch event examples in mobile web development. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help 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. This event is triggered when the user moves the finger into or out of an element. 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] The touch event is added using the DOM0 level event handler in some versions of the chrome simulator. Event 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(&#39;test&#39;)
  },
  showIndex, handleTouch;
 showIndex = function ( type ) {
  elesMap.touch_obj.innerHTML = type + &#39;:&#39; + (++stateMap[type + &#39;_index&#39;]);
 };
 handleTouch = function ( event ) {
  showIndex( event.type );
 };
 elesMap.touch_obj.addEventListener(&#39;touchstart&#39;, function(event){handleTouch(event);}); 
 elesMap.touch_obj.addEventListener(&#39;touchmove&#39;, function(event){handleTouch(event);});
 elesMap.touch_obj.addEventListener(&#39;touchend&#39;, function(event){handleTouch(event);});
 })(); 
</script>
</body>
</html>

300ms

300ms problem is when an element performs its function and There is a 300 millisecond interval between executing touch events. 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(&#39;test&#39;)
    },
    fnHide, onTouch;
   fnHide = function (type) {
    elesMap.touchObj.style.display = &#39;none&#39;;
   };
   onTouch = function (event) {
    fnHide();
   };
   elesMap.touchObj.addEventListener(&#39;touchstart&#39;, 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 link jump will be triggered. The default behavior of transfer. 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(&#39;test&#39;)
    },
    fnHide, onTouch;
   fnHide = function (type) {
    elesMap.touchObj.style.display = &#39;none&#39;;
   };
   onTouch = function (event) {
    setTimeout(function(){
     fnHide();
    },300);
   };
   elesMap.touchObj.addEventListener(&#39;touchstart&#39;, 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 in the middle layer to let the middle layer accept this transition. Transparent events and hide them later

4. Tap events are used at both the upper and lower levels, but the default behavior is inevitable

5. The touchstart event on the document prevents the default behavior.


document.addEventListener(&#39;touchstart&#39;,function(e){
  e.preventDefault();
})

Next, add the jump behavior of the a tag


##

a.addEventListener(&#39;touchstart&#39;,function(){
 window.location.href = &#39;https://cnblogs.com&#39;; 
})

However, this method has side effects, and it will As a result, the page cannot be scrolled, text cannot be selected, etc. If you need to restore the text selection behavior on an element, you can use prevent bubbling to restore


el.addEventListener(&#39;touchstart&#39;,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, and event flow. , default behavior, etc.

Take touchstart as an example, the sample code is as follows


<script>
  (function () {
   var
    elesMap = {
     touchObj: document.getElementById(&#39;test&#39;)
    },
    onTouch;
   onTouch = function (e) {
     console.log(e)
  };
   elesMap.touchObj.addEventListener(&#39;touchstart&#39;, function (event) { onTouch(event); });
  })(); 
 </script>

1. The currentTarget property returns the node to which the listening function of the event is being executed.

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、eventPhase属性返回一个整数值,表示事件目前所处的事件流阶段。0表示事件没有发生,1表示捕获阶段,2表示目标阶段,3表示冒泡阶段

5、bubbles属性返回一个布尔值,表示当前事件是否会冒泡。该属性为只读属性

6、cancelable属性返回一个布尔值,表示事件是否可以取消。该属性为只读属性


//事件流
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(&#39;test&#39;)
    },
    onTouch;
   onTouch = function (e) {
     elesMap.touchObj.innerHTML = &#39;touches:&#39; + e.touches.length
                  + &#39;<br>changedTouches:&#39; + e.changedTouches.length
                  + &#39;<br>targetTouches:&#39; + e.targetTouches.length;
   };
   elesMap.touchObj.addEventListener(&#39;touchstart&#39;, 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(&#39;test&#39;)
    },
    onTouch;
   onTouch = function (e) {
    var touch = e.changedTouches[0];
    elesMap.touchObj.innerHTML = &#39;clientX:&#39; + touch.clientX + &#39;<br>clientY:&#39; + touch.clientY
     + &#39;<br>pageX:&#39; + touch.pageX + &#39;<br>pageY:&#39; + touch.pageY
     + &#39;<br>screenX:&#39; + touch.screenX + &#39;<br>screenY:&#39; + touch.screenY
   };
   elesMap.touchObj.addEventListener(&#39;touchstart&#39;, function (event) { onTouch(event); });
  })();

相关推荐:

JS手机端touch事件计算滑动距离的方法

有关touch事件解析和封装的知识

javascript移动设备Web开发中对touch事件的封装实例_javascript技巧


The above is the detailed content of Detailed explanation of touch event examples in web development. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Web Speech API开发者指南:它是什么以及如何工作Web Speech API开发者指南:它是什么以及如何工作Apr 11, 2023 pm 07:22 PM

​译者 | 李睿审校 | 孙淑娟Web Speech API是一种Web技术,允许用户将语音数据合并到应用程序中。它可以通过浏览器将语音转换为文本,反之亦然。Web Speech API于2012年由W3C社区引入。而在十年之后,这个API仍在开发中,这是因为浏览器兼容性有限。该API既支持短时输入片段,例如一个口头命令,也支持长时连续的输入。广泛的听写能力使它非常适合与Applause应用程序集成,而简短的输入很适合语言翻译。语音识别对可访问性产生了巨大的影响。残疾用户可以使用语音更轻松地浏览

如何使用Docker部署Java Web应用程序如何使用Docker部署Java Web应用程序Apr 25, 2023 pm 08:28 PM

docker部署javaweb系统1.在root目录下创建一个路径test/appmkdirtest&&cdtest&&mkdirapp&&cdapp2.将apache-tomcat-7.0.29.tar.gz及jdk-7u25-linux-x64.tar.gz拷贝到app目录下3.解压两个tar.gz文件tar-zxvfapache-tomcat-7.0.29.tar.gztar-zxvfjdk-7u25-linux-x64.tar.gz4.对解

web端是什么意思web端是什么意思Apr 17, 2019 pm 04:01 PM

web端指的是电脑端的网页版。在网页设计中我们称web为网页,它表现为三种形式,分别是超文本(hypertext)、超媒体(hypermedia)和超文本传输协议(HTTP)。

web前端和后端开发有什么区别web前端和后端开发有什么区别Jan 29, 2023 am 10:27 AM

区别:1、前端指的是用户可见的界面,后端是指用户看不见的东西,考虑的是底层业务逻辑的实现,平台的稳定性与性能等。2、前端开发用到的技术包括html5、css3、js、jquery、Bootstrap、Node.js、Vue等;而后端开发用到的是java、php、Http协议等服务器技术。3、从应用范围来看,前端开发不仅被常人所知,且应用场景也要比后端广泛的太多太多。

Python轻量级Web框架:Bottle库!Python轻量级Web框架:Bottle库!Apr 13, 2023 pm 02:10 PM

和它本身的轻便一样,Bottle库的使用也十分简单。相信在看到本文前,读者对python也已经有了简单的了解。那么究竟何种神秘的操作,才能用百行代码完成一个服务器的功能?让我们拭目以待。1. Bottle库安装1)使用pip安装2)下载Bottle文件https://github.com/bottlepy/bottle/blob/master/bottle.py2.“HelloWorld!”所谓万事功成先HelloWorld,从这个简单的示例中,了解Bottle的基本机制。先上代码:首先我们从b

web前端打包工具有哪些web前端打包工具有哪些Aug 23, 2022 pm 05:31 PM

web前端打包工具有:1、Webpack,是一个模块化管理工具和打包工具可以将不同模块的文件打包整合在一起,并且保证它们之间的引用正确,执行有序;2、Grunt,一个前端打包构建工具;3、Gulp,用代码方式来写打包脚本;4、Rollup,ES6模块化打包工具;5、Parcel,一款速度极快、零配置的web应用程序打包器;6、equireJS,是一个JS文件和模块加载器。

深入探讨“高并发大流量”访问的解决思路和方案深入探讨“高并发大流量”访问的解决思路和方案May 11, 2022 pm 02:18 PM

怎么解决高并发大流量问题?下面本篇文章就来给大家分享下高并发大流量web解决思路及方案,希望对大家有所帮助!

web是前端还是后端web是前端还是后端Aug 24, 2022 pm 04:10 PM

web有前端,也有后端。web前端也被称为“客户端”,是关于用户可以看到和体验的网站的视觉方面,即用户所看到的一切Web浏览器展示的内容,涉及用户可以看到,触摸和体验的一切。web后端也称为“服务器端”,是用户在浏览器中无法查看和交互的所有内容,web后端负责存储和组织数据,并确保web前端的所有内容都能正常工作。web后端与前端通信,发送和接收信息以显示为网页。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)