移动端 touch事件

随着移动设备普及,鼠标事件无法满足触摸屏需求,触摸事件愈发重要。本文介绍了touchstart、touchmove、touchend等触摸事件类型,还探讨了同一对象同时绑定touch和click事件时,触摸并移动、触摸不移动的情况,以及touch模拟点击事件的效果。


前言

    随着智能手机和平板电脑的普及, 越来越多的人用移动设备浏览网页,我们平时在pc浏览器上用的鼠标事件,比如:click, mouseover等等, 已经无法满足移动设备触摸屏的特点,触摸时代的到来,离不开那些触摸事件。


一、事件类型

  • touchstart : 触摸开始(手指放在触摸屏上)
<div class="father">
        <div class="son"></div>
</div>
<script>
	  var son = document.getElementsByClassName("son")[0];
       son.addEventListener("touchstart", function() {
            console.log("触摸开始");

        });
</script>

在这里插入图片描述

  • touchmove : 拖动(手指在触摸屏上移动)
son.addEventListener("touchmove", function() {
            console.log("触摸中...");
        });

在这里插入图片描述

  • touchend : 触摸结束(手指从触摸屏上移开)
son.addEventListener("touchend", function() {
            console.log("触摸结束");
        });

在这里插入图片描述
执行顺序可看下图:
在这里插入图片描述

二、touch和click

当同一个对象同时绑定touch事件和点击事件:
 son.addEventListener("touchstart", function() {
            console.log("触摸开始");

        });
        son.addEventListener("touchmove", function() {
            console.log("触摸中...");
        });
        son.addEventListener("touchend", function() {
            console.log("触摸结束");
        });
        son.addEventListener("click", function() {
                console.log("点击");

            })

1.触摸并移动

在这里插入图片描述
可以发现,并没有触发点击事件

2.触摸不移动

在这里插入图片描述
我们发现如果触摸不移动就会触发点击事件,但是貌似点击事件比其他事件都要晚执行。我们是否能通过toch来模拟点击呢?

3.touch模拟点击

 // 定义一个变量, 给定一个假设值(开关思想)
        var isMove = false;
        son.addEventListener("touchmove", function() {
            isMove = true;
        });
        son.addEventListener("touchend", function() {
            if (!isMove) {
                console.log("这是触摸事件模拟的点击事件");

            }
            isMove = false;

        });
		//普通点击事件
        son.addEventListener("click", function() {
            console.log("点击事件");

        })

在这里插入图片描述
通过上图可发现通过touch模拟的点击事件,和普通点击事件触发时间近乎一致。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值