javascript ('ontouchstart' in window) 返回 true 但没有触摸事件

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

('ontouchstart' in window) returns true but no touch events

javascriptjqueryhtmljavascript-eventscordova

提问by epeleg

I am trying to write code that will run either in a browser or as a phonegap application. one of the things I need to do is to decide if I am in an environment that supports touch events or not.

我正在尝试编写可以在浏览器中或作为 phonegap 应用程序运行的代码。我需要做的一件事是决定我是否处于支持触摸事件的环境中。

my current problem is that my chrome (20.0.01132.47 m) returns truefor ('ontouchstart' in window)but it does not fire the touch events.

我现在的问题是,我的铬(20.0.01132.47米)的回报true('ontouchstart' in window),但它不会触发触摸事件。

When I open the Developer tools settings dialog (the gear icon on the bottom right of the Developer Tools). I get an option to "Emulate touch events". When I check this option the browser fires the touch events. but when it is not checked it does not fire the events but the detection I use still says that the touch events are available.

当我打开开发者工具设置对话框时(开发者工具右下角的齿轮图标)。我可以选择“模拟触摸事件”。当我选中此选项时,浏览器会触发触摸事件。但是当它没有被检查时它不会触发事件但是我使用的检测仍然说触摸事件可用。

Can I tell from script if "Emulate touch events" is enabled or not ?

我可以从脚本中判断是否启用了“模拟触摸事件”?

JQuery based answers are fine.

基于 JQuery 的答案很好。

回答by yckart

Can I tell from script if "Emulate touch events" is enabled or not ?

我可以从脚本中判断是否启用了“模拟触摸事件”?

Try to check for more than one finger ;-)

尝试检查多个手指;-)

Perhaps this helps?

也许这有帮助?

window.addEventListener('touchstart', function(event) {
    var emulate = event.targetTouches.length == 2;
    alert(emulate ? true : false);
}, false);


BTW: 'ontouchstart' in windowresults in false(chrome v21.0.1180.60) unless you have closedthe developer toolbar.

顺便说一句: 'ontouchstart' in window结果false(chrome v21.0.1180.60) 除非您关闭了开发人员工具栏。

Fiddle

小提琴

回答by Sanjib Debnath

Best way by js:

js的最佳方式:

function is_touch_device() {
    return 'ontouchstart' in window || navigator.maxTouchPoints;
}
console.log(is_touch_device())