jquery touchstart in browser

后端 未结 3 1338
一生所求
一生所求 2020-12-09 17:06

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

相关标签:
3条回答
  • 2020-12-09 17:17

    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.

    0 讨论(0)
  • 2020-12-09 17:21

    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);
    
    0 讨论(0)
  • 2020-12-09 17:41

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

    0 讨论(0)
提交回复
热议问题