浏览器中的 jquery touchstart
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9389968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery touchstart in browser
提问by coure2011
As touchstart/touchend is yet not supported in most of the desktop browsers. How can I create touchstart event that will be the same as mousedown event (that is supported in all browsers).
由于大多数桌面浏览器尚不支持 touchstart/touchend。如何创建与 mousedown 事件相同的 touchstart 事件(所有浏览器都支持)。
I want something like this
我想要这样的东西
$('obj').bind('touchstart', function(e){
});
will be translated into
将被翻译成
$('obj').bind('mousedown', function(e){
})
回答by alex
You can bind both at once...
你可以同时绑定两个...
$('obj').bind('touchstart mousedown', function(e){
});
If you want to mousedown
event to fire touchstart
events automatically (so you only need to bind touchstart
) use...
如果你想事件自动mousedown
触发touchstart
事件(所以你只需要绑定touchstart
)使用...
$(document).bind('mousedown', function(event) {
$(event.target).trigger('touchstart');
});
Note that this means mousedown
events must propagate to document
before the custom touchstart
event can be triggered. This could have unexpected side effects.
请注意,这意味着mousedown
事件必须传播到document
才能touchstart
触发自定义事件。这可能会产生意想不到的副作用。
回答by Eric Steinborn
Try something like this:
尝试这样的事情:
var clickEventType = ((document.ontouchstart!==null)?'click':'touchstart');
$('obj').bind(clickEventType, function(e){});
Better yet, use .on() for binding:
更好的是,使用 .on() 进行绑定:
$('body').on(clickEventType, 'obj', function(e){});
This checks document to see if touchstart exists, if it does, then your event is 'touchstart' if it doesn't (most desktop browsers) then its 'click'.
这会检查文档以查看 touchstart 是否存在,如果存在,则您的事件为“touchstart”,如果不存在(大多数桌面浏览器),则为“click”。
You can also trigger using the same event type:
您还可以使用相同的事件类型触发:
$('obj').trigger(clickEventType);
回答by Maciej Paprocki
It's not the nicest solution, but the best I found till now. Downfall? It only works after first touch happened so you cannot use synchronously :(
这不是最好的解决方案,而是我迄今为止发现的最好的解决方案。倒台?它仅在第一次触摸发生后有效,因此您无法同步使用:(
var isTouch = false;
$('body').on('touchstart', function () {
isTouch = true;
});
You can also check if browser support touch first with modernizr for example.
例如,您还可以检查浏览器是否首先使用 Modernizr 支持触摸。
Remember to don't use it in global scope (unless you have to). You can also change it to be modernizr "alike" by adding is-touch-device class to Html tag by adding after isTouch = true
code: $('html').addClass('is-touch-device')
. In this case you can reference it from everywhere (from css also).
记住不要在全局范围内使用它(除非你必须这样做)。您还可以通过添加以下isTouch = true
代码将 is-touch-device 类添加到 Html 标记,从而将其更改为“类似” $('html').addClass('is-touch-device')
。在这种情况下,您可以从任何地方(也从 css)引用它。