简体   繁体   中英

addClass when the screen resolution is less than 767px in JavaScript

I created a bootstrap menu, I need to add some classes and attributes when the screen resolution is less than 767 px. My code:

<li class="item-104 deeper parent">
  <a href="#">О министерстве</a>
    <ul class="nav-child unstyled small">
        <li class="item-113"><a href="#">Новости</a>
        </li>
        <li class="item-134"><a href="#">Подразделения Министерства</a>
        </li>
        <li class="item-135 deeper parent">
        <a href="#">Подведомственные учреждение министерства</a>
            <ul class="nav-child unstyled small">
                <li class="item-159"><a href="#">ФОК «ЖАР» МВД Республики Узбекистан</a>
                </li>
            </ul>
        </li>
        <li class="item-136"><a href="#">Прием на службу в органы внутренних дел</a>
        </li>
        <li class="item-177"><a href="#">Тендеры</a>
        </li>
    </ul>
</li>

<script>
    $(document).ready(function() {
      $(window).resize(function(){
        var windowWidth = $(window).width();
        if(windowWidth < 767)$(".navbar-nav ul").addClass("dropdown-menu") && $(".navbar-nav li",".navbar-nav ul").removeClass("parent","nav-child");
      });
    });
</script>

and I want to add the attribute data-toggle="dropdown" to the link which has a subdirectory with ul, ie <li><a href="#" data-toggle="dropdown"><ul><li> etc.

The problem seems to be with && between

$(".navbar-nav ul").addClass("dropdown-menu") and $(".navbar-nav li",".navbar-nav ul").removeClass("parent","nav-child");

Instead it should be like this

if (windowWidth < 767) {
      $(".navbar-nav ul").addClass("dropdown-menu");
      $(".navbar-nav li", ".navbar-nav ul").removeClass("parent", "nav-child");
    }

Also this same thing can be achieved using CSS media queries

Mediaqueries (as requested as an alternative)

@media screen and (max-width: 800px) {
  body {
    background-color: #FF0;
  }
}

This example changes the background-color of the body to yellow whenever the screen screen is less than 800 pixels.

How do you apply this in your case?

Apply all classes you wish to use beforehand, and wrap the markup of the classes that need to invoke in media queries.

@media screen and (max-width: 800px) {
  .dropdown-menu {
    /* CSS that invokes the dropdown */
  }
}
@media screen and (min-width: 801px) {
  .nav-child {
    /* CSS that is being used in medium / large screens */
  }
}

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