jquery touchstart in browser

烈酒焚心 提交于 2019-11-27 02:43:00

问题


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).

I want something like this

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

will be translated into

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

回答1:


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...

$(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.




回答2:


Try something like this:

var clickEventType = ((document.ontouchstart!==null)?'click':'touchstart');

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

Better yet, use .on() for binding:

$('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'.

You can also trigger using the same event type:

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



回答3:


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.

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).



来源:https://stackoverflow.com/questions/9389968/jquery-touchstart-in-browser

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