How can I detect device touch support in JavaScript?

后端 未结 4 626
孤城傲影
孤城傲影 2020-12-28 18:42

In the past, when detecting whether a device supports touch events in JavaScript, we could do something like this:

var touch_capable = (\'ontouchstart\' in d         


        
4条回答
  •  独厮守ぢ
    2020-12-28 19:16

    Well old question, but having to do this without a library, I created the following solution -- simply let the events talk for them self -- when you see the touch events, just disable the processing of the mouse events.

    In coffescript is would look like this;

               hasTouch = false
               mouseIsDown = false
               @divs.on "touchstart", (e)->
                  hasTouch = true
                  touchstart(e.timeStamp,e.originalEvent.touches[0].pageX);
                  return true
               @divs.on "mousedown", (e)->
                  mouseIsDown = true;
                  touchstart(e.timeStamp,e.clientX) if not hasTouch
                  return true
    
               @divs.on 'touchmove', (e) ->
                  touchmove(e.timeStamp,e.originalEvent.touches[0].pageX);
                  return true;
               @divs.on 'mousemove', (e) ->
                  touchmove(e.timeStamp,e.clientX) if mouseIsDown and not hasTouch 
                  return true;
    
               @divs.on 'touchend', (e) ->
                  touchend();
                  return true
               @divs.on 'mouseup', (e) ->
                  mouseIsDown = false;
                  touchend() if not hasTouch
                  return true
    

    The just define functions for touchstart,move and end containing the actual logic....

提交回复
热议问题