twitter-bootstrap 使用媒体查询添加/删除类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24786076/
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
Add/Remove classes using media queries
提问by Afflatus
My general question is how can one conditionally add or remove classes or ids to a particular class using css media queries alone? In the sample code below, for example, how could I add "Class_B" to all of the div's with "Class_A" when @media all and (max-width: 1000px) and (min-width: 700px)?
我的一般问题是如何单独使用 css 媒体查询有条件地向特定类添加或删除类或 ID?例如,在下面的示例代码中,如何将“Class_B”添加到所有带有“Class_A”的 div 中@media all and (max-width: 1000px) and (min-width: 700px)?
<div class="Class_A"><div>
My specific case: I'm using Twitter Bootstrap v3.2.0. I have a header with a series of buttons in it like so:
我的具体情况:我使用 Twitter Bootstrap v3.2.0。我有一个带有一系列按钮的标题,如下所示:
<button class="btn navbar-btn">FooA</button>
<button class="btn navbar-btn">FooB</button>
<button class="btn navbar-btn">FooC</button>
When the screen jumps from medium (md) to small(sm), I would like to add the class "btn-sm" to all of those elements. How can I do that most efficiently/elegantly?(I would prefer not to use JS or add any additional libraries if that's possible)
当屏幕从中 (md) 跳到小 (sm) 时,我想为所有这些元素添加类“btn-sm”。我怎样才能最有效/优雅地做到这一点?(如果可能的话,我宁愿不使用 JS 或添加任何其他库)
I realize I could add an arbitrary class to all those buttons like "btn-sm-duplicate" and only define it when the browser reaches a certain specification like the code below. However, it seems ugly to create a duplicate class when it's really not nec... Can you suggest something?
我意识到我可以向所有这些按钮添加一个任意类,例如“btn-sm-duplicate”,并且仅在浏览器达到特定规范时才定义它,如下面的代码。然而,当它真的不是 nec 时创建一个重复的类似乎很难看......你能提出一些建议吗?
@media all and (max-width: 1000px) and (min-width: 700px) {
btn-sm-duplicate{
::Copy/Paste all the attributes of btn-sm from bootstrap::
}
}
采纳答案by Steve Sanders
You cannot do this with CSS alone. One approach would be to take advantage of extendin a CSS pre-processor like LESS.
单独使用 CSS 无法做到这一点。一种方法是利用extend像 LESS 这样的 CSS 预处理器。
LESS example:
少示例:
@media (max-width: 991px) {
btn-sm-duplicate{
&:extend(.btn-sm);
}
}
Another approach would be to use Javascript to add the class based on screen size. A library like Modernizr.mqmakes this pretty easy.
另一种方法是使用 Javascript 根据屏幕大小添加类。像Modernizr.mq这样的库使这变得非常容易。

