How to check browser for touchstart support using JS/jQuery?

你说的曾经没有我的故事 提交于 2019-11-26 08:04:47

问题


In an attempt to follow best practices, we\'re trying to use the proper JavaScript/jQuery events according to what device you are using. For example, we\'re building a mobile site that has an tag that will have an onclick or touch event. In the case of an iPhone, we\'d like to use the \"touchstart\" event. We\'d like to test if their device supports \"touchstart\" before we bind that handler to the object. If it doesn\'t, then we will bind \"onclick\" instead.

What is the best way to do this?


回答1:


You can detect if the event is supported by:

if ('ontouchstart' in document.documentElement) {
  //...
}

Give a look to this article:

  • Detecting event support without browser sniffing

The isEventSupported function published there, is really good at detecting a wide variety of events, and it's cross-browser.




回答2:


Use this code to detect if the device supports touch.

Also work for windows 8 IE10 which uses 'MSPointerDown' event instead of 'touchmove'

var supportsTouch = false;
if ('ontouchstart' in window) {
    //iOS & android
    supportsTouch = true;

} else if(window.navigator.msPointerEnabled) {

    // Windows
    // To test for touch capable hardware 
    if(navigator.msMaxTouchPoints) {
        supportsTouch = true;
    }

}



回答3:


You could check if typeof document.body.ontouchstart == "undefined" to fall back to normal dom events




回答4:


I made a full demostration that works in every browser with the full source code of the solution of this problem: Detect touch screen devices in Javascript.



来源:https://stackoverflow.com/questions/2915833/how-to-check-browser-for-touchstart-support-using-js-jquery

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