CSS 使用媒体查询添加类或其他属性

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

Add class or other attribute using media query

javascriptiphonecssmedia-queries

提问by Alex K

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

我目前正在使用 CSS 媒体查询来定位一些像这样的中小屏幕设备:

@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?

有没有办法用 CSS 或者 JavaScript 来做到这一点?

采纳答案by user2168565

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

查看Enquire.js。用于处理媒体查询的轻量级纯 JavaScript 库。看起来很酷。

回答by Bart

It cannot be done with plain CSS.

它不能用普通的 CSS 来完成。

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

看看 LESS 或 SASS。它们旨在使使用CSS 更加动态和灵活。

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

SASS

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

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

回答by Synesso

A JavaScript solution

JavaScript 解决方案

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

回答by iConnor

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

看看conditionizr,这可能就是你要找的http://conditionizr.com/

回答by Павел Иванов

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

为此也可以帮助Modernizr- 即使启用了 svg 或其他功能也可以检测到。

http://modernizr.com/

http://modernizr.com/