解决部分安卓touchend不触发问题

本文详细解析了JavaScript的触屏事件touchstart、touchmove、touchend的特性与使用技巧,探讨了不同事件触发机制及四种常见解决方案,帮助开发者解决触屏事件在Android设备上的触发异常问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:
js的触屏事件,主要有三个事件:touchstart,touchmove,touchend。
这三个事件最重要的属性是 pageX和 pageY,表示X坐标,Y坐标。
touchstart=在触摸开始时触发事件
touchend=在触摸结束时触发事件
touchmove=这个事件比较奇怪,按道理在触摸到过程中不断激发这个事件才对,但是在我的 Android 中,在 touchstart 激发后激发一次,然后剩余的都和 touchend 差不多同时激发。
这三个事件都都有一个 timeStamp 的属性,查看 timeStamp 属性,可以看到顺序是 touchstart -> touchmove ->touchmove -> … -> touchmove ->touchend

第一种方案:
在监听touchstart或者touchmove事件的函数里,阻止事件的默认行为event.preventDefault(),那么到touchend就能正常触发

 <div class="btn" @touchstart="touchstart" @touchend="touchend"></div>
  touchend(event) {
  //松开按键
  event.preventDefault();
  }

第二种方案:
同时绑定touchcancel和touchend事件,这样在安卓上就能通过触发touchcancel来重新展示我们的按钮。

<div class="btn" @touchstart="touchstart" @touchend="touchend" @touchend="touchcancel"></div>
touchend(event) { 
//松开按键
}

第三种方案:
阻止任何父事件的 event.stopPropagation()行为,那么到touchend就能正常触发。

 <div class="btn" @touchstart="touchstart" @touchend="touchend"></div>
  touchend(event) {
  //松开按键
  //阻止任何父事件处理程序被执行
  event.stopPropagation();
  }

第四种方案:
问题:
如果触发了 touchmove, touchend 就不会被触发了, 而且 touchmove 没有持续触发。
解决方法:
只要在 touchstart 的时候调用下 event.preventDefault(); 即可让其他事件都正常被触发了。

$(document).on("touchstart",".btn-highlight",function(){
        $(this).addClass("hover");
    }).on("touchmove",".btn-highlight",function(event){
        event.preventDefault();
    }).on("touchcancel touchend",".btn-highlight",function(event){
        $(this).removeClass("hover");
    });
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值