当前位置: 首页 > 工具软件 > YDUI-Touch > 使用案例 >

关于移动端的touch事件(touchstart, touchmove, touchend,touchcancel)

梁丘成和
2023-12-01

移动端的touch事件

四种touch事件

touchstart: //手指放到屏幕上时触发

touchmove: //手指在屏幕上滑动式触发

touchend: //手指离开屏幕时触发

touchcancel: //系统取消touch事件的时候触发

<style>
	div{
	height:100px;
	width:100px;
	background-color:yellow;
	}
</style>
<body>
<div></div>
</body>
<script>
	//1.获取dom元素
	var div=document.querySelector('div');
	//2.添加事件
	//添加开始触摸事件,当手指触摸到屏幕时触发
	div.addEventListener('touchstart',function(){
		console.log('start');
	});
	//添加手指滑动事件,当手指在屏幕上滑动时触发,move事件是持续触发
	div.addEventListener('touchmove',function(){
		console.log('move');
	});
	//添加触摸结束事件,当手指离开屏幕时触发
	div.addEventListener('touchend',function(){
		console.log('end');
	});
	//添加意外中断事件
	div.addEventListener('touchcancel',function(){
		console.log('cancel');
	});
</script>

touchmove事件详释

用这个代码测试
var div=document.querySelector('div');
//开始触摸
div.addEventListener('touchstart',function(e){
	console,log(e.touches);
});

1,记录手指的起始位置–坐标
2.记录手指离开屏幕时的坐标值–记录手指在滑动过程中的坐标值
3.计算两个记录的手指坐标的差异
4.让dom元素也进行相应数值的偏移

touches: 是指当前屏幕所有的手指对象
targetTouches: 当前元素上的手指对象
changedTouches: 当前屏幕上变换的手指对象–从无到有,从有到无

*targetTouches与touches在测试中没有区别

手指对象的坐标

screenX/screenY:是手指的触摸点相对于屏幕左上角的坐标距离
clientX/clientY:相对于当前视口–移动端屏幕
pageX/pageY:相对于当前页面的内容–会有滚动条–包含滚动的

//拖拽操作--drag

var div=document.querySelector('div');
var startX,startY,moveX,moveY,distanceX,distanceY;
//开始触摸
//如果把div换成document事件,那么就能自动捕获到当前响应事件的对象,用的是e.target属性

div.addEventListener('touchstart',function(e){
	startX=e.targetTouches[0].clientX;
	startY=e.targetTouches[0].clientY;
});
//触摸滑动~持续
div.addEventListener('touchmove',function(e){
//记录手指滑动过程的坐标值
moveX=e.targetTouches[0].moveX;
moveY=e.targetTouches[0].moveY;
//计算与上一次坐标的差异
distanceX=moveX-startX;
distanceY=moveY-startY;
//设置偏移
//如果把div换成document事件,这里的div要换成e.target
div.style.transform='translate('+distanceX+'px',"+distanceY+'px')';
});
//触摸结束
div.addEventListener('touchend',function(e){
})

 类似资料: