jQuery change class on viewport smaller than 750px

天涯浪子 提交于 2020-01-16 18:47:13

问题


I have class .one, and when you view on mobile, on smaller viewport than 700px, I want change that class to .two ?

How is that possible, thanks?


回答1:


You can use the "resize" event :

$( window ).resize(function() {
    if ($(window).width() < 700 ) {
       $('.one').addClass('two').removeClass('one');
    } else {
        $('.two').addClass('one').removeClass('two');
    }
});



回答2:


I think you're trying to solve the wrong problem. Just because your viewport changes, does that mean the item the class is applied to is changing?

Instead, a neater way is use the same class (which, after all, is a way of describing the content) and a @media query to set the styling:

.myClass {
    font-weight: bold;
    font-size: 1.2em;
}

@media (max-width: 750px) {
    .myClass {
       font-size: 1.0em;
    }
}

See MDN for more details.




回答3:


Simple:

if ($(window).width() < 700) {
   $( "parentelement" ).removeClass( "one" ).addClass( "two" );
}

I'm sure you can even make it:

 if ($(window).width() < 700) {
       $( "body" ).removeClass( "one" ).addClass( "two" );
    }

To make all "one" classes replaces with class "two"

To make sure it works when a user resizes the browser window I would also enclose it in a window resize i.e:

 $(window).resize(function() {
       if ($(window).width() < 700) {
               $( "body" ).removeClass( "one" ).addClass( "two" );
            }
    });

Or to just have it on startup you can enclose it in a document ready:

$(document).ready(function() {
 if ($(window).width() < 700) {
               $( "body" ).removeClass( "one" ).addClass( "two" );
            }

});



回答4:


You can use:

$( window ).resize(function() {
 if ($(window).width() <= 700)
  $('.one').addClass('two').removeClass('one')
 else
  $('.two').addClass('one').removeClass('two')
}).trigger('resize');



回答5:


Get the size of the browser, and change the class accordingly. Keep a variable with the current state, so that you only change the class when the state changes.

For example, changing the class on the body element:

$(function(){

  setSize();
  $(window).resize(setSize);

  var isMobile = false;

  function setSize() {
    var w = $(window).width();
    if (w < 700 && !isMobile) {
      isMobile = true;
      $('body').removeClass('one').addClass('two');
    } else if (w >= 700 && isMobile) {
      isMobile = false;
      $('body').removeClass('two').addClass('one');
    }
  }

});


来源:https://stackoverflow.com/questions/24430512/jquery-change-class-on-viewport-smaller-than-750px

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!