jQuery.on“touchstart mousedown” – 两个事件都在触摸屏设备上触发
我的问题是我无法取消触发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
检查是否存在touchstart
支持,设置变量以确定您提供的支持:
//touchstart or mousedown var click = ('ontouchstart' in document.documentElement) ? 'touchstart' : 'mousedown';
然后使用:
$(element).on(click,function(){ //do stuff });
请注意,此实例中的click
是变量,而不是字符串。
- 检测支持哪些事件 – 无需同时支持这两个事件
- 相应地加载$ .on()
-
在添加事件之前删除所有传播的事件和/或预先存在的(不需要的)事件不会成为问题
$(“#mobileMenuBtn”)。off()。on({“touchstart mousedown”:$ .proxy(this.onMenuInteraction,this)});
参考文献:
如何做检查浏览器的换touchstart支持-使用JS-的jQuery
jquery的:关闭()
结合JDA和Dave Methvin的上述建议(感谢两者),我的问题的解决方案如下。
在“touchstart mousedown”事件的回调中,我专门关闭了“touchstart mousedown”。 这将停止任何后续触摸或鼠标事件被调用。
我发现使用Android的原生浏览器实现’touchend’问题 – 但是’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 } ); } })
希望这有助于其他人找到同样的问题。
使用e.preventDefault();
如果touchstart
被触发,则取消mousedown
事件。