支持悬停的设备的媒体查询 [英] Media query for devices supporting hover

查看:144
本文介绍了支持悬停的设备的媒体查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为支持悬停的浏览器(例如桌面浏览器)和不支持的浏览器(例如触摸屏设备)提供单独的行为。具体而言,我想在支持它的浏览器上声明悬停状态,但不希望浏览器不支持这种悬停状态,以免移动浏览器通过多次轻敲来模拟它,因为这会打破页面上的其他交互 - 通过不定义悬停对于这些浏览器来说,这是可以避免的。



我已经阅读了互动媒体查询功能,它看起来应该做的伎俩。我可以这样做:

  @media(hover:none){
/ * behavior for触摸浏览器* /
}

根据 CanIUse 它可在我需要支持的所有浏览器上使用,IE11和Firefox除外。



所以我想知道我是否可以这样做 - 因为主要的触摸设备都支持它,然后否定它:

  @media not(hover:none){
/ *桌面浏览器行为* /
}

但是,这似乎并不奏效。



伪代码示例:我试图做的事情:

  .myelement {
/ *一些样式* /
/ *注意:这里没有悬停状态* /
$ b $media $(这个设备支持悬停){
.myelement:hover {
/ *更多样式* /
}
}

那么,有没有一种方式使这项工作的方式,或者我在错误的轨道?

解决方案

感谢德克尔的评论我解决了这通过运行JS中的逻辑和应用类来实现:

eg

  const canHover =!(matchMedia('(hover:none)')。matches); 
if(canHover){
document.body.classList.add('can-hover');

然后在样式表中:

  .myElement {
background:blue;
}
.can-hover .myElement:hover {
background:red;
}

我已在台式机Chrome,Safari和Firefox以及iOS Safari并按预期工作。


I'd like to provide separate behaviour for browsers supporting hover (e.g. desktop browsers) and ones which don't (e.g. touchscreen devices). Specifically I want to declare a hover state on browsers that support it, but not for browsers that don't, so as to avoid having mobile browsers emulate it with extra taps, as this breaks other interactions on the page - by not defining a hover state for those browsers this is avoided.

I've read up on the Interaction Media Queries feature and it looks like it should do the trick. I'd be able to do something like:

@media (hover: none) {
  /* behaviour for touch browsers */
}

According to CanIUse it is available on all the browsers I need to support except IE11 and Firefox.

So I wondered if I could do it the other way around - since the main touch devices all support it, then negate it:

@media not (hover: none) {
  /* behaviour for desktop browsers */
}

However, this doesn't seem to work at all.

Pseudocode example of what I'm trying to do:

.myelement {
  /* some styling */
  /* note: no hover state here */
}
@media(this device supports hover) {
  .myelement:hover {
    /* more styling */
  }
}

So, is there a way to make this work in the way intended, or am I down the wrong track?

解决方案

Thanks to Dekel's comments I solved this by running the logic in JS and applying a class instead:

e.g.

const canHover = !(matchMedia('(hover: none)').matches);
if(canHover) {
  document.body.classList.add('can-hover');
}

Then in the stylesheet:

.myElement {
  background: blue;
}
.can-hover .myElement:hover {
  background: red;
}

I've tested this on desktop Chrome, Safari and Firefox, and iOS Safari and it works as expected.

这篇关于支持悬停的设备的媒体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆