Javascript css媒体查询向HTML添加类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29593944/
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
css media query adding class to HTML
提问by CharlesF
I have this HTML:
我有这个 HTML:
<li><a href=""><i class="fa fa-iconname" style="vertical-align: middle;"></i>Link Name</a></li>
I am then using this media query in my CSS:
然后我在我的 CSS 中使用这个媒体查询:
@media (max-width: 1000px) {
...
}
how can i change my tag to:
如何将我的标签更改为:
<i class="fa fa-iconname lg-2x" style="vertical-align: middle;"></i>
when the media query takes effect?
媒体查询什么时候生效?
回答by AndrewL64
You can use pure css to achieve this by just replicating the list-item and toggle with media query like this:
您可以使用纯 css 来实现这一点,只需复制列表项并切换媒体查询,如下所示:
HTML:
HTML:
<li class="bigScreen"><a href=""><i class="fa fa-iconname"></i>Link Name</a></li>
<li class="smallScreen"><a href=""><i class="fa fa-iconname lg-2x"></i>Link Name</a></li>
CSS:
CSS:
@media (max-width: 1000px) {
.bigScreen {
display:none;
}
.smallScreen {
display:block;
}
}
@media (min-width: 1001px) {
.bigScreen {
display:block;
}
.smallScreen {
display:none;
}
}
回答by Jacob Gray
CSS is just a styling language, it cannot actually edit the HTML.
CSS 只是一种样式语言,它实际上无法编辑 HTML。
If you want to actually make changes to the HTML, use javascript:
如果要实际更改 HTML,请使用 javascript:
jQuery:
jQuery:
var $homeIcon = $('.fa-iconname');
$(window).resize(function() {
if (window.innerWidth <= 1000) $homeIcon.addClass('lg-2x');
else $homeIcon.removeClass('lg-2x');
});
Vanilla JS:
香草JS:
var homeIcon = document.querySelector('.fa-home');
window.onResize = function() {
if (window.innerWidth <= 1000) homeIcon.classList.add('lg-2x');
else homeIcon.classList.remove('lg-2x');
};
回答by Danko
You can not do that with css, but you can with JavaScript or jQuery.
你不能用 css 做到这一点,但你可以用 JavaScript 或 jQuery。
fa-2x is essentialy: font-size: 2em;. So, you can do this:
fa-2x 本质上是:font-size: 2em;。所以,你可以这样做:
@media (max-width: 1000px) {
.fa-iconname {
font-size: 2em;
}
}
回答by Shelly
Toggle class lg-2x on element li when the window size is less than 1000px .
当窗口大小小于 1000px 时,在元素 li 上切换类 lg-2x 。
$( window ).resize(function() {
if($(window).width() <=1000) {
$('i').toggleClass(function() {
if ( $( this ).is( ".lg-2x" ) ) {
console.log("class already there good to go");
} else {
$( this ).addClass("lg-2x");
}
}
}else{
$('i').removeClass("lg-2x");
}
});
回答by ste
You can create an equivalent class for bigger screen and leave it empty:
您可以为更大的屏幕创建一个等效的类并将其留空:
@media (min-width: 1000px) {
.lg-2x {
/* empty class */
}
}
and assign it to the html element from the beginning.
并从头开始将其分配给 html 元素。

