最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add class or other attribute using media query - Stack Overflow

programmeradmin9浏览0评论

I'm currently using CSS media queries to target some small/medium screen devices like this:

@media screen and (min-device-width: 480px) {
  ...
}
@media screen and (min-device-width: 720px) {
  ...
}

This works as expected, and I can apply styles to some particular selectors, but.. What I was wondering is if there is a way to add a class or other attribute to a selector based on media query.

Example of my thought:

@media screen and (min-device-width: 480px) {
  body { addClass('body-iphone') }
}

Is there a way to do that with CSS or maybe JavaScript?

I'm currently using CSS media queries to target some small/medium screen devices like this:

@media screen and (min-device-width: 480px) {
  ...
}
@media screen and (min-device-width: 720px) {
  ...
}

This works as expected, and I can apply styles to some particular selectors, but.. What I was wondering is if there is a way to add a class or other attribute to a selector based on media query.

Example of my thought:

@media screen and (min-device-width: 480px) {
  body { addClass('body-iphone') }
}

Is there a way to do that with CSS or maybe JavaScript?

Share Improve this question asked Feb 22, 2013 at 11:14 Alex KAlex K 7,2179 gold badges43 silver badges64 bronze badges 3
  • stackoverflow./questions/4801224/… - this sounds like solving your issue – Daniel Ursu Commented Feb 22, 2013 at 11:20
  • @Daniel, almost yes, but it only works for all devices (desktops too), i would like to find a way to use min-device-width to make sure this isn't just a small 13" laptop screen – Alex K Commented Feb 22, 2013 at 11:22
  • well then, you should also check the user agent. quirksmode/js/detect.html – Daniel Ursu Commented Feb 22, 2013 at 11:29
Add a ment  | 

5 Answers 5

Reset to default 9

Check out Enquire.js. Lightweight, pure JavaScript library for handling media queries. Looks pretty cool.

It cannot be done with plain CSS.

Have a look at LESS or SASS. They are designed to make working with CSS more dynamic and flexible.

  • http://lesscss
  • http://sass-lang.

Once you use them. You can't live without them.


In case you want to add a existing class selector to the body on certain resolutions.

SASS

.some-style { background-color:red; }

@media screen and (min-device-width: 480px) {
    body {
        @extend .some-style;
    }
}

A JavaScript solution

if (window.matchMedia("(min-device-width: 480px)").matches) {
    // modify dom
}   

Edit:missing closing parenthesis

take a look at conditionizr this could be what your looking for http://conditionizr./

For this also can help Modernizr - can detect even if svg enabled or other features is enabled.

http://modernizr./

发布评论

评论列表(0)

  1. 暂无评论