html5 判断是点击还是长按
在移动端尤其是微信浏览器中,长按有一个功能是识别二维码或者是弹出复制文字的浮层,但是有时候我们不想让他弹出来,于是会采用禁止默认事件的方式来写,那么问题来了,点击事件也就不生效了。于是可以采用另一种方法来实现它
在移动端有一个事件为touch事件,分为touchstart、touchend和touchmove。具体思路就是有一个延时器,在touchstart设置执行,延时器开始执行,touchend和touchmove事件触发时执行clearTimeout,将延时器清除。具体代码情况下方
var timeOutEvent = null; $("#touchArea").on({ touchstart:function(e){ timeOutEvent = setTimeout('longPress',500); e.preventDefault(); }, touchmove:function(){ clearTimeout(timeOutEvent); timeOutEvent = null; }, touchend:function(){ clearTimeout(timeOutEvent); if(!timeOutEvent){ alert("这是执行点击,而不是长按"); } return false; } }) function longPress(){ timeOutEvent = null; alert("长按事件触发"); }