touch事件
touchstart 手指触摸到一个DOM元素时触发
touchmove 手指在一个DOM元素上滑动时触发
touchend 手指在一个DOM元素移开时触发
ele.addEventListener('touchstart',function(){})
触摸事件对象(TouchEvent)
TouchEvent是一类描述手指在触摸屏幕的状态变化的事件。这类事件用于描述一个或多个触点,使开发者可以检测触点的移动,增加和减少,等等。
touchstart,touchmove ,touchend 都有各自的事件对象
touches 正在触摸屏幕的所有手指的一个列表
targetTouches 正在触摸单前DOM元素上的手指的一个列表
changedTouches 手指状态发送了变化,从无到有,从有到无变化
触摸的位置:targetTouches[0] 里面的pageX pageY
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 150px;
height: 150px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector("div")
div.addEventListener("touchstart",function(e){
console.log("touchstart",e)
})
div.addEventListener("touchmove",function(e){
console.log("touchmove",e)
})
div.addEventListener("touchend",function(e){
console.log("touchend",e)
// 记录离开的触点 changedTouches
})
</script>
</body>
</html>
移动端拖动元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector("div")
var startX = 0, startY = 0, // 手指初始坐标
x = 0, y = 0; // 盒子原来的位置
div.addEventListener("touchstart",function(e){
startX = e.targetTouches[0].pageX;
startY = e.targetTouches[0].pageY;
x = this.offsetLeft
y = this.offsetTop
})
div.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() //防止屏幕滚动
})
div.addEventListener("touchend",function(e){
})
</script>
</body>
</html>