移动端基本事件

一、基础事件

1、PC端事件

a)onclick 鼠标点击触发
b)onmousedown 鼠标按下触发
c)onmousemove 鼠标移动触发
d)onmouseup 鼠标抬起触发

2、移动端触屏事件

a) ontouchstart 手指按下触发
b) ontouchmove 手指移动触发
c) onTouchend 手指抬起触发

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <title>wwg</title>
  <style>
    body{font-family:"Microsoft yahei";}
    body,dl,dd,p,h1,h2,h3,h4,h5,h6{margin:0;}
    ol,ul,li{margin:0;padding:0;list-style:none;}
    img{border:none;display: block;}
    a{text-decoration: none; color: inherit;}
    input{outline: none;}
    .fl{float: left;}
    .fr{float: right;}    
    .clearfix::after{display: block; content: ""; clear: both;}
    
    #touch {
      width: 200px;
      height: 200px;
      background: #f0f;
    }
  </style>
</head>
<body>
  <div id="touch"></div>

  <script>
    let touch = document.getElementById('touch');

    // 手指按下 === 鼠标按下
    touch.addEventListener('touchstart', function (e) {
      console.log(e)
      console.log(e.touches)
      console.log(e.touches[0]) // 常用属性
      console.log(e.touches.length) // length表示手指的个数
      this.style.backgroundColor = "deeppink"
    })

    // 手指按下后移动 === 鼠标按下后移动
    let n = 0;
    touch.addEventListener('touchmove', function (e) {
      this.innerHTML = n++;
      this.style.backgroundColor = "#0f0";
    })

    // 手指抬起 === 鼠标抬起
    touch.addEventListener('touchend', function () {
      this.style.backgroundColor = "red";
    })


  </script>
</body>
</html>
3、PC端事件和移动端事件的区别

a)通过on的方式添加touch事件在谷歌模拟器下无效
b) 通过on的方式添加事件会前后覆盖
c) 鼠标事件在移动端可以使用,但有300毫秒的延迟

4、事件监听

a) addEventListener(‘不带on的事件名’,事件函数,是否冒泡 )事件绑定
b) 绑定多少个事件就执行多少个,不会存在前后事件覆盖的问题
c) 在谷歌模拟器下一直识别
d) 冒泡 从下往上,把事件一直向上传递,点击最下面的元素,最下面先执行
e) 捕获 从上往下,把事件一直向下传递,点击最上面的元素,最上面先执行

5、event对象

a) 标准事件函数默认的第一个参数
b) 是描述发生事件的详细信息

6、阻止默认事件

a) 事件默认行为:当一个事件发生的时候浏览器自己会默认做的事情
b) 比如正常情况下,鼠标可以拖拽图片,a标签跳转,手指长按可以选中文字,右键菜单等
c) e.preventDefault( ) 阻止默认行为,且解决在IOS上有网页回弹的橡皮筋现象
d) 但网页上的所有滚动条失效
e) 一般不会阻止默认

7、阻止冒泡

a) 在需要的时候的,标准用e.stopPropagation( ) 阻止冒泡问题,比如有时需要复制文本

8、事件点透问题

a) PC端鼠标事件,在移动端也可以正常使用,事件的执行会有300毫秒的延迟
b) 问题的产生是,点击了页面之后,浏览器会记录点击下去的坐标
c) 300毫秒之后,在该坐标找到现在的元素,执行该事件

9、点透问题解决办法

a) 阻止默认事件,但在部分安卓机不支持
b) 不用a标签做页面跳转,用window.location.href做跳转,比如移动端淘宝
c) 在移动端不用鼠标事件

10、防止误触问题

a) 用JS做判断,手指移动就不跳转,没有移动,说明是点击,就跳转

11、获取手指信息

a) touches 当前屏幕上的手指列表
b) targetTouches 当前元素上的手指列表
c) changedTouches 触发当前事件的手指列表
d) 获取手指的个数 e.changedTouches.length
e) 获取坐标 e.changedTouches[0].pageX

12、手指对象的区别

a) 在touchend的时候想要获取手指列表,只能用changedTouches
b) 原因在于,手指抬起了,也就没有touches,targetTouches了,只能用changedTouches

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值