如果设备宽度小于给定的宽度值,如何将类添加到html div id?

This is my current div id with no class:

<div id="my-id">
some content
</div>

After the following check (pseudo code),

if @media (max-width: 767px) {
==add "the-new-class" to the div id==
}

my div should be as follow:

<div id="my-id" class="the-new-class">
some content
</div>

No matter if is used jQuery or php. Tnx.

This should do the trick:

$(function() {
    $(window).resize(function(){
          if(window.matchMedia('(min-width: 767px)')){
               $('#id').addClass('someClassName');
          }else{
               $('#id').removeClass('someClassName');
          }
    });
});

It uses Jquery and the new matchMedia function. This functions matches the way the browsers css engine calculates the width of a window.

you can easily do it using jquery:

$(window).setsize(function() {
  var currentwidth = $(window).width();
  if(currentwidth <= 767)
  {
     $('#my-id').addClass('the-new-class');
  }
  else
  {
     $('#my-id').removeClass('the-new-class');
  }
})

Try this code with javascript:

<script>
 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
 console.log(width);
 if(width > 500)
 {
   document.getElementById('my-id').setAttribute("class", "the-new-class");
 }
</script>