简体   繁体   English

使用 Javascript 检测触摸屏设备

[英]Detecting touch screen devices with Javascript

In Javascript/jQuery, how can I detect if the client device has a mouse?在 Javascript/jQuery 中,如何检测客户端设备是否有鼠标?

I've got a site that slides up a little info panel when the user hovers their mouse over an item.我有一个网站,当用户将鼠标悬停在一个项目上时,它会向上滑动一个小信息面板。 I'm using jQuery.hoverIntent to detect the hover, but this obviously doesn't work on touchscreen devices like iPhone/iPad/Android.我正在使用 jQuery.hoverIntent 来检测悬停,但这显然不适用于 iPhone/iPad/Android 等触摸屏设备。 So on those devices I'd like to revert to tap to show the info panel.因此,在这些设备上,我想恢复为点击以显示信息面板。

var isTouchDevice = 'ontouchstart' in document.documentElement;

Note : Just because a device supports touch events doesn't necessarily mean that it is exclusively a touch screen device.注意:仅仅因为设备支持触摸事件并不一定意味着它只是一个触摸屏设备。 Many devices (such as my Asus Zenbook) support both click and touch events, even when they doen't have any actual touch input mechanisms.许多设备(例如我的 Asus Zenbook)支持点击和触摸事件,即使它们没有任何实际的触摸输入机制。 When designing for touch support, always include click event support and never assume any device is exclusively one or the other.在设计触摸支持时,始终包括单击事件支持,并且永远不要假设任何设备都是唯一的一种或另一种。

Found testing for window.Touch didn't work on android but this does:发现 window.Touch 的测试在 android 上不起作用,但这样做:

function is_touch_device() {
  return !!('ontouchstart' in window);
}

See article: What's the best way to detect a 'touch screen' device using JavaScript?请参阅文章: 使用 JavaScript 检测“触摸屏”设备的最佳方法是什么?

+1 for doing hover and click both. +1 用于hoverclick两者。 One other way could be using CSS media queries and using some styles only for smaller screens / mobile devices, which are the ones most likely to have touch / tap functionality.另一种方法可能是使用 CSS 媒体查询并仅将某些样式用于较小的屏幕/移动设备,这些设备最有可能具有触摸/点击功能。 So if you have some specific styles via CSS, and from jQuery you check those elements for the mobile device style properties you could hook into them to write you mobile specific code.因此,如果您通过 CSS 有一些特定的样式,并且从 jQuery 中检查这些元素的移动设备样式属性,您可以将它们挂钩以编写特定于移动设备的代码。

See here: http://www.forabeautifulweb.com/blog/about/hardboiled_css3_media_queries/见这里: http : //www.forabeautifulweb.com/blog/about/hardboiled_css3_media_queries/

if ("ontouchstart" in window || navigator.msMaxTouchPoints) {
    isTouch = true;
} else {
    isTouch = false;
}

Works every where !!无处不在!

return (('ontouchstart' in window)
      || (navigator.maxTouchPoints > 0)
      || (navigator.msMaxTouchPoints > 0));

Reason for using maxTouchPoints alongwith msMaxTouchPoints:使用 maxTouchPoints 和 msMaxTouchPoints 的原因:

Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using maxTouchPoints instead. Microsoft 已声明从 Internet Explorer 11 开始,可能会删除此属性的 Microsoft 供应商前缀版本 (msMaxTouchPoints),并建议改用 maxTouchPoints。

Source : http://ctrlq.org/code/19616-detect-touch-screen-javascript来源: http : //ctrlq.org/code/19616-detect-touch-screen-javascript

Google Chrome seems to return false positives on this one:谷歌浏览器似乎在这个问题上返回误报:

var isTouch = 'ontouchstart' in document.documentElement;

I suppose it has something to do with its ability to "emulate touch events" (F12 -> settings at lower right corner -> "overrides" tab -> last checkbox).我想这与它“模拟触摸事件”的能力有关(F12 -> 右下角的设置 -> “覆盖”选项卡 -> 最后一个复选框)。 I know it's turned off by default but that's what I connect the change in results with (the "in" method used to work in Chrome).我知道默认情况下它是关闭的,但这就是我将结果更改与(用于在 Chrome 中工作的“in”方法)联系起来的原因。 However, this seems to be working, as far as I have tested:但是,据我测试,这似乎有效:

var isTouch = !!("undefined" != typeof document.documentElement.ontouchstart);

All browsers I've run that code on state the typeof is "object" but I feel more certain knowing that it's whatever but undefined :-)我运行该代码的所有浏览器都声明typeof是“对象”,但我更确定知道它不是未定义的任何东西:-)

Tested on IE7, IE8, IE9, IE10, Chrome 23.0.1271.64, Chrome for iPad 21.0.1180.80 and iPad Safari.在 IE7、IE8、IE9、IE10、Chrome 23.0.1271.64、Chrome for iPad 21.0.1180.80 和 iPad Safari 上测试。 It would be cool if someone made some more tests and shared the results.如果有人进行更多测试并分享结果,那就太酷了。

Wrote this for one of my sites and probably is the most foolproof solution.为我的一个网站写了这个,可能是最简单的解决方案。 Especially since even Modernizr can get false positives on touch detection.尤其是因为即使是 Modernizr 也会在触摸检测上出现误报。

If you're using jQuery如果你使用 jQuery

$(window).one({
  mouseover : function(){
    Modernizr.touch = false; // Add this line if you have Modernizr
    $('html').removeClass('touch').addClass('mouse');
  } 
});

or just pure JS...或者只是纯 JS ...

window.onmouseover = function(){ 
    window.onmouseover = null;
    document.getElementsByTagName("html")[0].className += " mouse";
}

For my first post/comment: We all know that 'touchstart' is triggered before click.对于我的第一篇文章/评论:我们都知道“touchstart”是在点击之前触发的。 We also know that when user open your page he or she will: 1) move the mouse 2) click 3) touch the screen (for scrolling, or ... :) )我们也知道,当用户打开您的页面时,他或她将:1) 移动鼠标 2) 单击 3) 触摸屏幕(用于滚动,或... :))

Let's try something :让我们尝试一下:

//--> Start: jQuery //--> 开始:jQuery

var hasTouchCapabilities = 'ontouchstart' in window && (navigator.maxTouchPoints || navigator.msMaxTouchPoints);
var isTouchDevice = hasTouchCapabilities ? 'maybe':'nope';

//attach a once called event handler to window

$(window).one('touchstart mousemove click',function(e){

    if ( isTouchDevice === 'maybe' && e.type === 'touchstart' )
        isTouchDevice = 'yes';
});

//<-- End: jQuery //<-- 结束:jQuery

Have a nice day!有一个美好的一天!

I use:我使用:

if(jQuery.support.touch){
    alert('Touch enabled');
}

in jQuery mobile 1.0.1在 jQuery 移动 1.0.1 中

I have tested following code mentioned above in the discussion我已经测试了上面讨论中提到的以下代码

 function is_touch_device() {
    return !!('ontouchstart' in window);
 }

works on android Mozilla, chrome, Opera, android default browser and safari on iphone... all positive ...适用于 android Mozilla、chrome、Opera、android 默认浏览器和 iphone 上的 safari ......所有这些都是积极的......

seems solid for me :)对我来说似乎很可靠:)

A helpful blog post on the subject, linked to from within the Modernizr source for detecting touch events.关于该主题的一篇有用的博客文章,链接到用于检测触摸事件的 Modernizr 源。 Conclusion: it's not possible to reliably detect touchscreen devices from Javascript.结论:不可能从 Javascript 可靠地检测触摸屏设备。

http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

This works for me:这对我有用:

function isTouchDevice(){
    return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}

If you use Modernizr , it is very easy to use Modernizr.touch as mentioned earlier.如果您使用Modernizr ,则使用前面提到的Modernizr.touch非常容易。

However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.但是,为了安全起见,我更喜欢结合使用Modernizr.touch和用户代理测试。

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)如果你不使用 Modernizr,你可以简单地将上面的Modernizr.touch函数替换为('ontouchstart' in document.documentElement)

Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone .另请注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的 Microsoft 移动设备。

Also see this SO question 另请参阅此问题

In jQuery Mobile you can simply do:在 jQuery Mobile 中,您可以简单地执行以下操作:

$.support.touch

Don't know why this is so undocumented.. but it is crossbrowser safe (latest 2 versions of current browsers).不知道为什么这是没有记录的……但它是跨浏览器安全的(当前浏览器的最新 2 个版本)。

As already mentioned, a device may support both mouse and touch input.如前所述,设备可能同时支持鼠标和触摸输入。 Very often, the question is not "what is supported" but "what is currently used".很多时候,问题不是“支持什么”,而是“当前使用什么”。

For this case, you can simply register mouse events (including the hover listener) and touch events alike.对于这种情况,您可以简单地注册鼠标事件(包括悬停侦听器)和类似的触摸事件。

element.addEventListener('touchstart',onTouchStartCallback,false);

element.addEventListener('onmousedown',onMouseDownCallback,false);

...

JavaScript should automatically call the correct listener based on user input. JavaScript 应该根据用户输入自动调用正确的侦听器。 So, in case of a touch event, onTouchStartCallback will be fired, emulating your hover code.因此,如果发生触摸事件,将触发onTouchStartCallback ,模拟您的悬停代码。

Note that a touch may fire both kinds of listeners, touch and mouse.请注意,触摸可能会触发两种侦听器,触摸和鼠标。 However, the touch listener goes first and can prevent subsequent mouse listeners from firing by calling event.preventDefault() .但是,触摸侦听器首先执行,并且可以通过调用event.preventDefault()来阻止后续的鼠标侦听器触发。

function onTouchStartCallback(ev) {
    // Call preventDefault() to prevent any further handling
    ev.preventDefault();
    your code...
}

Further reading here . 在这里进一步阅读。

For iPad development I am using:对于 iPad 开发,我正在使用:

  if (window.Touch)
  {
    alert("touchy touchy");
  }
  else
  {
    alert("no touchy touchy");
  }

I can then selectively bind to the touch based events (eg ontouchstart) or mouse based events (eg onmousedown).然后我可以有选择地绑定到基于触摸的事件(例如 ontouchstart)或基于鼠标的事件(例如 onmousedown)。 I haven't yet tested on android.我还没有在安卓上测试过。

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

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