Javascript 如何使用 JS/jQuery 检查浏览器是否支持 touchstart?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2915833/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:28:18  来源:igfitidea点击:

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

javascriptjqueryiphonemobileunobtrusive-javascript

提问by Alex

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.

为了遵循最佳实践,我们尝试根据您使用的设备使用正确的 JavaScript/jQuery 事件。例如,我们正在构建一个移动网站,该网站的标签将具有点击或触摸事件。对于 iPhone,我们想使用“touchstart”事件。在我们将该处理程序绑定到对象之前,我们想测试他们的设备是否支持“touchstart”。如果没有,那么我们将绑定“onclick”。

What is the best way to do this?

做这个的最好方式是什么?

回答by CMS

You can detect if the event is supported by:

您可以通过以下方式检测事件是否受支持:

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

Give a look to this article:

看看这篇文章:

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

isEventSupported那里发布的函数非常擅长检测各种事件,而且它是跨浏览器的。

回答by George Filippakos

Use this code to detect if the device supports touch.

使用此代码来检测设备是否支持触摸。

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

也适用于使用“MSPointerDown”事件而不是“touchmove”的 Windows 8 IE10

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;
    }

}

回答by antimatter15

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

您可以检查是否typeof document.body.ontouchstart == "undefined"回退到正常的 dom 事件

回答by Manuel Ignacio López Quintero

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.

我做了一个完整的演示,可以在每个浏览器中使用这个问题的解决方案的完整源代码:Detect touch screen devices in Javascript