即使设置了preventDefault,鼠标事件仍会在触摸事件上触发 [英] mouse event still fired on touch event even with preventDefault set

查看:92
本文介绍了即使设置了preventDefault,鼠标事件仍会在触摸事件上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里误解了什么吗?我经常在网站上使用以下代码,希望在台式机和iPad设备上使用该代码:

is there anything I misunderstood here? I often use code like the following in my site that I want to work either for desktop and iPad device:

$("#someElement")
    .on( "mousemove", function(e) {         
        alert ( "I am still here" );
        // undesired code for ipad here
    } )
    .on( "touchmove", function(e) {
        e.preventDefault();
        // only desired code for ipad use here
    } );

我在许多地方读到e.preventDefault应该杀死附加的鼠标事件.并且触摸事件首先被阐述.但是,我现在意识到该警报仍在我的ipad上触发.为什么?有什么暗示吗?预先感谢!

I read in many places that the e.preventDefault should kill the mouse events attached. And that the touch events are elaborated in the first place. Yet, I now recognized that the alert is still triggered on my ipad. Why? Any hints on that? Thanks in advance!

我意识到,当我使用"touchstart"而不是"touchmove"时,e.preventDefault()可以按预期的方式工作.来,伙计们,一些想法!

I realized that when I put 'touchstart' instead of 'touchmove' the e.preventDefault() works in the predicted way. Come on, guys, some ideas!

推荐答案

向用户代理检查ipad.只需使用三叉戟运算符即可获得更简单的代码

Check with user agent for ipad.simply use trenary operator for more simple code

var isIPad = navigator.userAgent.match(/iPad/i) != null;

$("#someElement").on(((isIPad)? "touchmove" : "mousemove" ), 
                         ((isIPad)? gotoIpad : gotoOthers ));

function gotoIpad() {

      alert("I am ipad");
}

function gotoOthers() {

      alert("I am not ipad");
}

这篇关于即使设置了preventDefault,鼠标事件仍会在触摸事件上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆