简体   繁体   English

需要基于不同的屏幕尺寸在CSS中更改DIV的类

[英]Need to change class in CSS for a DIV based on different screen sizes

Need to change class in CSS for a DIV based on different screen sizes 需要基于不同的屏幕尺寸在CSS中更改DIV的类

<div id="tab" class="tab_small"></div>

I need to change class of DIV having ID "tab" to "tab_small","tab_medium" & "tab_large" based on the screen size using css only 我只需要使用CSS根据屏幕大小将ID为“ tab”的DIV的类别更改为“ tab_small”,“ tab_medium”和“ tab_large”

@media(max-width:450px){tab_small class will apply} 
@media(min-width:450px) and (max-width:768px){tab_medium will apply}
@media(min-width:768px) and (max-width:990px){tab_large will apply}

Is that doable? 那可行吗?

with JS I can do, Is there a way to do with CSS in bootstrap? 我可以用JS做,有没有办法在Bootstrap中处理CSS?

If all three classes will be there in HTML on that DIV, is there a way to display one out of them in html based on screen sizes? 如果所有三个类都将在该DIV上的HTML中存在,是否有一种方法可以根据屏幕大小在html中显示其中三个?

Thanks in advance! 提前致谢!

I think you are trying to achieve a behavior like this. 我认为您正在尝试实现这种行为。 Try to resize the fiddle window. 尝试调整小提琴窗口的大小。 Please be aware that setting a property within #tab selector will override the @media queries, if you want to prevent this behavior just use #tab .tab_small , #tab .tab_medium , #tab .tab_large selectors inside the @media queries. 请注意,内设置属性#tab选择将覆盖@media查询,如果你想阻止这一行为只是使用#tab .tab_small#tab .tab_medium#tab .tab_large选择内部@media查询。

#tab{
    width: 200px;
    height: 200px;
}
@media(max-width:450px){
    .tab_small{
       background:red;
    }
} 
@media(min-width:450px) and (max-width:768px){
    .tab_medium{
       background: green;
    }
}
@media(min-width:768px) and (max-width:990px){
    .tab_large{
       background: blue;
    }
}

Fiddle Demo 小提琴演示

Try this jQuery js solution, probably this will resolve your issue.. 试试这个jQuery js解决方案,可能会解决您的问题。

<div id="tab" class=""></div>
<script type="text/javascript">
if($('body').width() < 450){
    $('#tab').addClass('tab_small');
}else if($('body').width() > 450 && $('body').width() < 768){
   $('#tab').addClass('tab_medium');
}else{
    $('#tab').addClass('tab_large');
}
</script>

There is not way to change DOM property value using CSS. 无法使用CSS更改DOM属性值。 There is only way to achieve this using javascript. 只有使用javascript才能实现此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM