jQuery.on“touchstart mousedown” - 两个事件都在触摸屏设备上触发

时间:2014-08-27 08:59:05

标签: javascript jquery html5 mobile

我的问题是我无法取消触发touchstart后触发的mousedown事件。此问题特定于Android的本机浏览器。

Chrome和Safari都在Android和iOS(onMenuInteraction)中成功执行了以下方法。我的问题似乎仅限于Android的原生浏览器(对于我预装的Android 4.1.2)。

以下是我从Javascript对象中提取的代码。

MenuButtonView.prototype.onSmallScreenSetUp = function() {
    $("#mobileMenuBtn").on( { "touchstart mousedown": $.proxy( this.onMenuInteraction, this ) } );
}

MenuButtonView.prototype.onMenuInteraction = function(e) {
    console.log( this, "onMenuInteraction", e );
    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();
}

请有人告诉我如何取消手指触摸屏幕触发touchstart事件后触发的mousedown事件。

此要求基于管理与桌面和移动/平板电脑平台的互动。在您使用Android原生浏览器进行测试之前,一切正常。

非常感谢

d

4 个答案:

答案 0 :(得分:8)

检查是否存在touchstart支持,设置变量以确定您提供的支持:

//touchstart or mousedown
var click = ('ontouchstart' in document.documentElement)  ? 'touchstart' : 'mousedown';

然后使用:

$(element).on(click,function(){
    //do stuff
}); 

请注意,此实例中的click是变量,而不是字符串。

答案 1 :(得分:2)

如果e.preventDefault();被触发,请使用mousedown取消touchstart个事件。

答案 2 :(得分:1)

  1. 检测支持哪些事件 - 无需同时支持这两个事件
  2. 相应地加载$ .on()
  3. 在添加事件之前删除所有传播的事件和/或预先存在的(不需要的)事件不会成为问题

    $(" #mobileMenuBtn")。off()。on({" touchstart mousedown":$ .proxy(this.onMenuInteraction,this)});

  4. 参考文献:

    how-to-check-browser-for-touchstart-support-using-js-jquery

    jquery:off()

答案 3 :(得分:1)

结合JDA和Dave Methvin的上述建议(感谢两者),我的问题的解决方案如下。

在" touchstart mousedown"的回调中事件我专门关闭" touchstart mousedown"。这将停止任何后续触摸或鼠标事件被调用。

我发现实施' touchend'使用Android的原生浏览器会出现问题 - 但是' mouseup'事件似乎很好地涵盖了这两个目的,即,对我来说,它似乎表现得与你期望的那样表现出来' touchend'。

当' mouseup'我被称为然后重新申请" touchstart和mousedown"事件到按钮。

我的解决方案的简化版本如下:

$(document).ready( function() {

        $("#mobileMenuBtn").on( { "touchstart mousedown" : onInteraction,
                                  "mouseup" : onInteractionEnd } );

        function onInteraction(e) {
            $("#mobileMenuBtn").off( "touchstart mousedown" );
        }

        function onInteractionEnd(e) {
            $("#mobileMenuBtn").on( { "touchstart mousedown" : onInteraction } );
        }

})

希望这可以帮助其他人找到同样的问题。

相关问题