即使设置了preventDefault,鼠标事件仍会触发事件触发

时间:2014-07-10 05:50:55

标签: javascript jquery touch mouseevent preventdefault

这里有什么我误解的吗?我经常在我的网站中使用以下代码,我想要为桌面和iPad设备工作:

$("#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上触发。为什么?有什么提示吗?提前谢谢!

编辑: 我意识到当我把触摸开始时#t;而不是触摸移动' e.preventDefault()以预测的方式工作。来吧,伙计们,一些想法!

2 个答案:

答案 0 :(得分:1)

使用用户代理检查ipad.simply使用三元运算符来获得更简单的代码

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");
}

答案 1 :(得分:0)

试试这个用户代理

    var isTouch = /iPad/i.test(navigator.userAgent);

            if(isTouch ){
            $("#someElement").on( "touchmove", function(e) {
                       // only desired code for ipad use here
                } );
            }
     else{
            $("#someElement")
                .on( "mousemove", function(e) {         
                    alert ( "I am still here" );
                    // undesired code for ipad
                });
            }
相关问题