浏览器中的jquery touchstart

由于大多数桌面浏览器尚不支持touchstart / touchend。 如何创建与mousedown事件相同的touchstart事件(所有浏览器都支持)。

我想要这样的东西

$('obj').bind('touchstart', function(e){ }); 

将被翻译成

 $('obj').bind('mousedown', function(e){ }) 

你可以一次绑定两个……

 $('obj').bind('touchstart mousedown', function(e){ }); 

如果你想mousedown事件自动触发touchstart事件(所以你只需要绑定touchstart )使用…

 $(document).bind('mousedown', function(event) { $(event.target).trigger('touchstart'); }); 

请注意,这意味着在触发自定义touchstart事件之前, mousedown事件必须传播到document 。 这可能有意想不到的副作用。

尝试这样的事情:

 var clickEventType = ((document.ontouchstart!==null)?'click':'touchstart'); $('obj').bind(clickEventType, function(e){}); 

更好的是,使用.on()进行绑定:

 $('body').on(clickEventType, 'obj', function(e){}); 

这会检查文档是否存在touchstart,如果存在,那么您的事件是“touchstart”(如果不存在)(大多数桌面浏览器)然后是“click”。

您还可以使用相同的事件类型触发:

 $('obj').trigger(clickEventType); 

这不是最好的解决方案,但是我发现的最好的解决方案。 倒台? 它只在第一次触摸发生后才能工作,所以你不能同步使用:(

  var isTouch = false; $('body').on('touchstart', function () { isTouch = true; }); 

您还可以检查浏览器支持是否首先与modernizr联系。

切记不要在全局范围内使用它(除非你必须)。 您还可以通过在isTouch = true code: $('html').addClass('is-touch-device')之后添加is-touch-device类来将其更改为modernizr“相似”。 在这种情况下,您可以从任何地方引用它(也来自css)。