简体   繁体   English

如何通过Android和iOS上的Javascript检测设备上的触摸?

[英]How to detect touch on a devise through Javascript across Android and iOS?

I've certain functionality on a web page that I'd like to render only if the browser doesn't support touch. 我在网页上有某些功能,只有在浏览器不支持触摸时才会呈现。 After a lot of googling, I've found out the following code, and it works, but it just works on Android, and doesn't work on iOS devices: 经过大量的谷歌搜索,我发现了以下代码,它可以工作,但它只适用于Android,并不适用于iOS设备:

function supportsTouch() {
    return ('onstarttouch' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)
}

I've also tried Modernizr , and written the following script to detect the touch capability on a device: 我也尝试过Modernizr ,并编写以下脚本来检测设备上的触摸功能:

function supportsTouch() {
  if (Modernizr.touchevents) {
    return true;
  }
}

But it works on neither OS. 但它既不适用于操作系统。 I know that it's not possible to actually detect that either a devise responds to physical touch or not according to this , but is there any hack that could possibly tell me about touch capability of a devise on both platforms: iOS and Android? 我知道实际上不可能根据这个实际检测出设计是否响应物理触摸,但有没有任何黑客可以告诉我两个平台上的设备的触摸功能:iOS和Android?

Note: I'd not go with the option of media queries, because that would contaminate my web application as anyone can change the width of a browser on a desktop machine. 注意:我不会选择媒体查询,因为这会污染我的Web应用程序,因为任何人都可以更改桌面计算机上浏览器的宽度。

After a lot of struggle, I finally managed to get a few lines of code that detect touch for Android as well as iOS devices, and here is the final function: 经过大量的努力,我终于设法获得了几行代码来检测Android和iOS设备的触摸,这是最终的功能:

function supportsTouch() {
    return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0) || (typeof el.ongesturestart == "function")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM