简体   繁体   中英

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.

I want have five items in one row so I'm running 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

 $('.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 .

Is this possible?

You wouldn't even need javscript for this, use 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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