Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

css - Media query for devices supporting hover

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

not should prefix media type (screen, print, all, etc) and not media feature (hover, point, etc).

Wrong:

@media not (hover: none)

Correct:

@media not all and (hover: none)

Yes, its unintuitive and weird. Source (see comments).

So you do not need javascript to alternate result of media query.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...