TouchEvent事件用于描述一个或多个触点,使我们可以检测触点的移动、触点的增加和减少。
touchstart、touchmove、touchend三个事件都有各自的事件对象。
常见的三个对象/触摸列表:
触摸列表 | 说明 |
---|---|
touches | 正在触摸屏幕的所有手指的一个列表 |
targetTouches | 正在触摸当前DOM上的手指的一个列表 |
changedTouches | 手指状态发生了改变的列表,从无到有,从有到无变化 |
如果touches和targetTouches侦听的是同一个DOM元素,得到的结果/长度length是一样的。
在实际开发中经常使用的是targetTouches。
targetTouches[0]可以得到正在触摸的DOM元素的第一个手指的相关信息,比如手指的坐标等。
var box = document.querySelector(".box");
box.addEventListener("touchstart",function(e){
// 会输出一个TouchEvent事件对象,事件对象里重点学习三个常见的对象列表
console.log(e);
// 第一个对象列表touches console.log(e.touches);
// 第二个对象列表touches console.log(e.targetTouches);
// 如果touches和targetTouches侦听的是同一个DOM元素,得到的结果/长度length是一样的
// targetTouches[0]可以得到正在触摸的DOM元素的第一个手指的相关信息,比如手指的坐标等
console.log(e.targetTouches[0]);
})
box.addEventListener("touchend",function(e){
// 当手指离开DOM元素时,touches和targetTouches的长度length就为0了,因为手指离开了,所以就没有了
// 但changedTouches的长度length是1,因为它是从有到无,可以记录
console.log(e);
})