常见touch事件

使用方法示例:

对象列表:
白话解释:
touchues:一 个 TouchList 对象,包含了所有当前接触触摸平面触点的 Touch 对象;有一个手指触摸屏幕,里面的length就是1,两个手指触摸就是2
targetTouches:一个 TouchList 对象;触摸当前dom对象的触点(触摸某一块的手指数量),而不是触摸屏幕的数量
重点:
因为平时我们都是给元素注册触摸事件,所以重点记住targetTocuhes
用法示例:
<div class="box">div>
<script>
var box = document.querySelector('.box')
box.addEventListener('touchstart', function(e){
//我们一般都是触摸元素,所以经常使用targetTouches
console.log(e.targetTouches[0]);
//targetTouches[0],就可以得到正在触摸dom元素的第一个手指相关信息(比如坐标)
})
script>
触摸(点击)后打印台结果:


HTML代码:
<style>
.box{
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: pink;
}
style>
head>
<body>
<div class="box">div>
<script>
var box = document.querySelector('.box')
var X = 0;//获得盒子原来的位置
var Y = 0;
box.addEventListener('touchstart', function(e){
//获得手指的初始坐标
startX = e.targetTouches[0].pageX;
startY = e.targetTouches[0].pageY;
X = this.offsetLeft;
Y = this.offsetTop;
})
box.addEventListener('touchmove', function(e){
//计算移动的距离
var moveX = e.targetTouches[0].pageX -startX;
var moveY = e.targetTouches[0].pageY -startY;
this.style.left = X + moveX + 'px';
this.style.top =Y + moveY + 'px';
e.preventDefault();
})
script>
body>