mouse event still fired on touch event even with preventDefault set

ε祈祈猫儿з 提交于 2020-01-24 22:35:27

问题


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

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!

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


回答1:


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



回答2:


try this user agent

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


来源:https://stackoverflow.com/questions/24669312/mouse-event-still-fired-on-touch-event-even-with-preventdefault-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!