简体   繁体   English

如何仅在特定屏幕尺寸下将CSS类与脚本一起应用?

[英]How can I apply a CSS class with my script only at certain screen sizes?

I'm using bootstrap 4 and my markup is running through a for loop which produces eight item divs. 我正在使用引导程序4,并且我的标记正在通过for loop运行,该for loop会产生八个item div。

I want have five items in one row so I'm running col-2 . 我想在一排有五个项目,所以我要运行col-2 But obviously that'll show six in one row. 但是很明显,它将连续显示六个。

Since I cannot add the offset in the markup (because it's in a for loop), I've added it via JS 由于我无法在标记中添加偏移量(因为它位于for循环中),因此我通过JS添加了它

 $('.item:nth-child(5n+1)').addClass('offset-1'); 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <div class="test"> <div class="container"> <div class="row justify-content-center"> <div class="item col-2"> <p>test 1</p> </div> <div class="item col-2"> <p>test 2</p> </div> <div class="item col-2"> <p>test 3</p> </div> <div class="item col-2"> <p>test 4</p> </div> <div class="item col-2"> <p>test 5</p> </div> <div class="item col-2"> <p>test 6</p> </div> <div class="item col-2"> <p>test 7</p> </div> <div class="item col-2"> <p>test 8</p> </div> </div> </div> </div> 

However, I only want that JS to run at min-width: 1440px . 但是,我只希望JSmin-width: 1440px

Is this possible? 这可能吗?

You wouldn't even need javscript for this, use CSS. 为此,您甚至不需要javscript,请使用CSS。 Simply add another class: 只需添加另一个类:

@media(min-width: 1440px){
  .col-5{
    width: 20%;
  }
}

try this, buddy 尝试一下,哥们

if (window.innerWidth >= 1440) {
    console.log(window.innerWidth)
    ...
    // your code here
}

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

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