Have you tried using this function?
(您是否尝试过使用此功能?)
(This is the same as Modernizr used to use.)((这与Modernizr过去使用的相同。))
function is_touch_device() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } } console.log(is_touch_device());
UPDATE 1
(更新1)
document.createEvent("TouchEvent")
have started to return true
in the latest chrome (v. 17).
(document.createEvent("TouchEvent")
已开始在最新的镶边( document.createEvent("TouchEvent")
中返回true
。)
Modernizr updated this a while ago.(Modernizr前不久对此进行了更新。)
Check Modernizr test out here .(在此处检查Modernizr测试 。)
Update your function like this to make it work:
(像这样更新您的功能以使其工作:)
function is_touch_device1() { return 'ontouchstart' in window; } console.log(is_touch_device1());
UPDATE 2
(更新2)
I found that the above wasn't working on IE10 (returning false on MS Surface).
(我发现以上内容不适用于IE10(在MS Surface上返回false)。)
Here is the fix:(解决方法是:)
function is_touch_device2() { return 'ontouchstart' in window // works on most browsers || 'onmsgesturechange' in window; // works on IE10 with some false positives }; console.log(is_touch_device2());
UPDATE 3
(更新3)
'onmsgesturechange' in window
will return true in some IE desktop versions so thats not reliable.
(在某些IE桌面版本'onmsgesturechange' in window
将返回true,因此并不可靠。)
This works slightly more reliably:(这可以更可靠地工作:)
function is_touch_device3() { return !!('ontouchstart' in window // works on most browsers || navigator.maxTouchPoints); // works on IE10/11 and Surface }; console.log(is_touch_device3());
UPDATE 2018
(更新2018)
Time goes by and there are new and better ways to test this.
(随着时间的流逝,有更多更好的新方法可以对此进行测试。)
I've basically extracted and simplified Modernizr's way of checking it:(我基本上已经提取并简化了Modernizr的检查方式:)
function is_touch_device4() { var prefixes = ' -webkit- -moz- -o- -ms- '.split(' '); var mq = function(query) { return window.matchMedia(query).matches; } if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { return true; } // include the 'heartz' as a way to have a non matching MQ to help terminate the join // https://git.io/vznFH var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''); return mq(query); } console.log(is_touch_device4());
Here they are using the non-standard touch-enabled
media query feature, which I think is kinda weird and bad practice.
(在这里,他们使用的是非标准的支持touch-enabled
媒体查询功能,我认为这是一种怪异和不道德的做法。)
But hey, in the real world I guess it works.(但是,嘿,在现实世界中,我认为它是可行的。)
In the future (when they are supported by all) those media query features could give you the same results: pointer
and hover
.(将来(当所有人都支持它们时),这些媒体查询功能可以为您提供相同的结果: pointer
和hover
。)
Check out the source of how Modernizr are doing it .
(查阅Modernizr如何执行此操作的来源 。)
For a good article that explains the issues with touch detection, see: Stu Cox: You Can't Detect a Touchscreen .
(有关解释触摸检测问题的好文章,请参阅: Stu Cox:您无法检测到触摸屏 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…