移动端事件(touchstart、touchmove、touchend)--移动端开发整理笔记(三)

移动端事件

三个事件

  • touchstart 手指触摸 相当于PC端 mousedown
  • touchend 手指抬起 相当于PC端 mouseup
  • touchmove 手指滑动 相当于PC端 mousmove

注意: touch事件在chrome的模拟器下,部分版本通过on的方式来添加事件无效,这时候需要事件监听的方法 addEventListener("事件名",函数,冒泡或捕获),它有以下优点:

  1. 不会存在事件前后覆盖问题

  2. 在chrome的模拟器下可以一直识别

写法如下:

box.addEventListener(
	"touchstart",
	function(ev) {
		console.log(1);
	}
);

阻止默认事件

box.addEventListener(
	"touchstart",
	function(ev) {
		console.log(1);
	}
);
ev.preventDefault();  // 阻止默认事件

以上阻止掉:document touchstart的默认事件,可以解决一下问题:

  1. 阻止页面上的文字被选中 -- 可以通过阻止冒泡使某个元素上的文字被选中

  2. 阻止页面上的系统菜单

隐患: 页面上的所有滚动条失效

阻止 document的 touchstart 或者 touchmove,可以清除系统默认的回弹

事件点透

在移动端 PC事件(如mouseover) 有 300ms的延迟

  1. 点击了页面之后,浏览器会记录点击下去的坐标

  2. 300ms后,在该坐标找到现在在这的元素 执行事件

解决方法:

  1. 阻止默认事件 (部分安卓机型不支持)

  2. 不在移动端使用鼠标事件,不用a标签做页面跳转

防止误触

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,user-scalable=no" />
		<title>无标题文档</title>
		<style>
			a {
				display: block;
				 50px;
				height: 50px;
				background: red;
				color: #fff;
				margin: 20px;
			}
		</style>
		<script>

		/*防止误触,先清除掉浏览器的默认事件  这时候 点击a标签失效不会跳转 手机浏览器的自带滚动条失效*/
			document.addEventListener(
				"touchstart",
				function(e) {
					e.preventDefault();
				}
			); 
			window.onload = function () {
				var a = document.querySelectorAll("a");
				for(var i = 0; i < a.length; i++) {
					a[i].addEventListener(
						"touchmove",
						function() {
							this.isMove = true; //给当前元素添加自定义属性isMove 让他等于true; 如果在元素上移动以后就等于true
						}
					);
					a[i].addEventListener(
						"touchend",
						function() {
							if(!this.isMove) {
								window.location.href = this.href;  //这里判断 的是如果没有移动的话就是点击。根据当前元素的链接通过window.location.href跳转
							}
							this.isMove = false; //跳转完成以后恢复到false
						}
					);
				}
			};
		</script>
	</head>
	<body>
		<a href="http://www.baidu.com">百度</a>
		<a href="http://www.baidu.com">百度</a>
		<a href="http://www.baidu.com">百度</a>
		<a href="http://www.baidu.com">百度</a>
		<a href="http://www.baidu.com">百度</a>
	</body>
</html>

touchEvent

  1. touches 当前屏幕上的手指列表

  2. targetTouches 当前元素上的手指列表

  3. changedTouches 触发当前事件的手指列表

每个Touch对象包含的属性如下。

  • clientX:触摸目标在视口中的x坐标。

  • clientY:触摸目标在视口中的y坐标。

  • identifier:标识触摸的唯一ID。

  • pageX:触摸目标在页面中的x坐标。

  • pageY:触摸目标在页面中的y坐标。

  • screenX:触摸目标在屏幕中的x坐标。

  • screenY:触摸目标在屏幕中的y坐标。

  • target:触目的DOM节点目标。

  • force: 压力大小,是从0.0(没有压力)到1.0(最大压力)的浮点数

原文地址:https://www.cnblogs.com/ylweb/p/7588925.html