CSS 媒体查询以检测设备是否为触摸屏

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

Media query to detect if device is touchscreen

csstouchmedia-queries

提问by JJJollyjim

What is the safest way, using media queries, to make something happen when not on a touchscreen device? If there is no way, do you suggest using a JavaScript solution such as !window.Touchor Modernizr?

当不在触摸屏设备上时,使用媒体查询最安全的方法是什么?如果没有办法,您是否建议使用诸如!window.Touch或 Modernizr 之类的 JavaScript 解决方案?

采纳答案by Starx

I would suggest using modernizrand using its media query features.

我建议使用Modernizr并使用其媒体查询功能。

if (Modernizr.touch){
   // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
   // bind to normal click, mousemove, etc
}

However, using CSS, there are pseudo class like, for example in Firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browser.

但是,使用 CSS,有伪类,例如在 Firefox 中。您可以使用:-moz-system-metric(touch-enabled)。但这些功能并非适用于所有浏览器。

For Appledevices, you can simple use:

对于苹果设备,你可以简单的使用:

if(window.TouchEvent) {
   //.....
}

Especially for Ipad:

特别是对于 Ipad:

if(window.Touch) {
    //....
}

But, these do not work on Android.

但是,这些不适用于 Android

Modernizrgives feature detection abilities, and detecting features is a good way to code, rather than coding on basis of browsers.

Modernizr提供了特征检测能力,检测特征是一种很好的编码方式,而不是基于浏览器进行编码。

Styling Touch Elements

样式化触摸元素

Modernizer adds classes to the HTML tag for this exact purpose. In this case, touchand no-touchso you can style your touch related aspects by prefixing your selectors with .touch. e.g. .touch .your-container. Credits: Ben Swinburne

Modernizer 正是为此目的将类添加到 HTML 标签中。在这种情况下,touch并且no-touch使您可以通过.touch前缀您选择风格你触摸相关的方面。例如.touch .your-container学分:本·斯威本

回答by Znarkus

There is actually a property for this in the CSS4 media query draft.

CSS4 媒体查询草案中实际上有一个属性。

The ‘pointer' media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:

‘none'
- The input mechanism of the device does not include a pointing device.

‘coarse'
- The input mechanism of the device includes a pointing device of limited accuracy.

‘fine'
- The input mechanism of the device includes an accurate pointing device.

'pointer' 媒体功能用于查询指针设备(如鼠标)的存在和准确性。如果设备有多种输入机制,建议 UA 报告主要输入机制中功能最差的指点设备的特性。此媒体查询采用以下值:

'none'
- 设备的输入机制不包括定点设备。

'粗略'
- 设备的输入机制包括精度有限的指点设备。

'fine'
- 设备的输入机制包括一个精确的定位设备。

This would be used as such:

这将被这样使用:

/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
    input[type="checkbox"], input[type="radio"] {
        min-width:30px;
        min-height:40px;
        background:transparent;
    }
}

I also found a ticketin the Chromium project related to this.

我还在Chromium 项目中找到了一张与此相关的票

Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):

浏览器兼容性可以在Quirksmode测试。这些是我的结果(2013 年 1 月 22 日):

  • Chrome/Win: Works
  • Chrome/iOS: Doesn't work
  • Safari/iOS6: Doesn't work
  • Chrome/Win:有效
  • Chrome/iOS:不起作用
  • Safari/iOS6:不起作用

回答by Simon East

The CSS solutions don't appear to be widely available as of mid-2013. Instead...

截至 2013 年年中,CSS 解决方案似乎并未广泛使用。反而...

  1. Nicholas Zakas explainsthat Modernizr applies a no-touchCSS class when the browser doesn't support touch.

  2. Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:

    <script>
        document.documentElement.className += 
        (("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
    </script>
    

    Then you can write your CSS as:

    .no-touch .myClass {
        ...
    }
    .touch .myClass {
        ...
    }
    
  1. Nicholas Zakas 解释说no-touch当浏览器不支持触摸时,Modernizr 会应用一个CSS 类。

  2. 或者用一段简单的代码在 JavaScript 中检测,允许你实现你自己的类似 Modernizr 的解决方案:

    <script>
        document.documentElement.className += 
        (("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
    </script>
    

    然后你可以将你的 CSS 写成:

    .no-touch .myClass {
        ...
    }
    .touch .myClass {
        ...
    }
    

回答by Alex W

Media types do not allow you to detect touch capabilities as part of the standard:

媒体类型不允许您检测触摸功能作为标准的一部分:

http://www.w3.org/TR/css3-mediaqueries/

http://www.w3.org/TR/css3-mediaqueries/

So, there is no way to do it consistentlyvia CSS or media queries, you will have to resort to JavaScript.

因此,无法通过 CSS 或媒体查询始终如一地做到这一点,您将不得不求助于 JavaScript。

No need to use Modernizr, you can just use plain JavaScript:

无需使用 Modernizr,您可以使用纯 JavaScript:

<script type="text/javascript">
    var is_touch_device = 'ontouchstart' in document.documentElement;
    if(is_touch_device) alert("touch is enabled!");
</script>

回答by Soko?ow

In 2017, CSS media query from second answer still doesn't work on Firefox. I found a soluton for that: -moz-touch-enabled

2017 年,来自第二个答案的 CSS 媒体查询在 Firefox 上仍然不起作用。我为此找到了一个解决方案:-moz-touch-enabled



So, here is cross-browser media query:

所以,这是跨浏览器媒体查询:

@media (-moz-touch-enabled: 1), (pointer:coarse) {
    .something {
        its: working;
    }
}

回答by Buzut

There is actually a media query for that:

实际上有一个媒体查询:

@media (hover: none) { … }

Apart from Firefox, it's fairly well supported. Safari and Chrome being the most common browsers on mobile devices, it might suffice untill greater adoption.

除了 Firefox,它的支持相当不错。Safari 和 Chrome 是移动设备上最常见的浏览器,它可能就足够了,直到被更多人采用。

回答by aleksa_95

This will work. If it doesn't let me know

这将起作用。如果它不让我知道

@media (hover: none) and (pointer: coarse) {
    /* Touch screen device style goes here */
}

edit: hover on-demand is not supported anymore

编辑:不再支持按需悬停

回答by Patrick W. McMahon

This solution will work until CSS4 is globally supported by all browsers. When that day comes just use CSS4. but until then, this works for current browsers.

此解决方案将一直有效,直到所有浏览器都支持 CSS4。当那一天到来时,只需使用 CSS4。但在那之前,这适用于当前的浏览器。

browser-util.js

浏览器util.js

export const isMobile = {
  android: () => navigator.userAgent.match(/Android/i),
  blackberry: () => navigator.userAgent.match(/BlackBerry/i),
  ios: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  opera: () => navigator.userAgent.match(/Opera Mini/i),
  windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (isMobile.android() || isMobile.blackberry() || 
  isMobile.ios() || isMobile.opera() || isMobile.windows())
};

onload:

负载:

old way:

旧方法:

isMobile.any() ? document.getElementsByTagName("body")[0].className += 'is-touch' : null;

newer way:

较新的方式:

isMobile.any() ? document.body.classList.add('is-touch') : null;

The above code will add the "is-touch" class to the body tag if the device has a touch screen. Now any location in your web application where you would have css for :hover you can call body:not(.is-touch) the_rest_of_my_css:hover

如果设备有触摸屏,上面的代码会将“is-touch”类添加到 body 标签中。现在,您可以在 Web 应用程序中拥有 css for :hover 的任何位置都可以调用body:not(.is-touch) the_rest_of_my_css:hover

for example:

例如:

button:hover

becomes:

变成:

body:not(.is-touch) button:hover

This solution avoids using modernizer as the modernizer lib is a very big library. If all you're trying to do is detect touch screens, This will be best when the size of the final compiled source is a requirement.

此解决方案避免使用 Modernizer,因为 Modernizer 库是一个非常大的库。如果您要做的只是检测触摸屏,那么当需要最终编译源的大小时,这将是最好的。

回答by Robin Mehdee

I was able to resolve this issue using this

我能够使用这个解决这个问题

@media (hover:none), (hover:on-demand) { 
Your class or ID{
attributes
}    
}

回答by Matoeil

adding a class touchscreen to the body using JS or jQuery

使用 JS 或 jQuery 向主体添加类触摸屏

  //allowing mobile only css
    var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
    if(isMobile){
        jQuery("body").attr("class",'touchscreen');
    }