jQuery : Add class dynamically depending on the browser window resolution

自闭症网瘾萝莉.ら 提交于 2019-12-02 17:47:49

If you aren't storing any other classes on the body element, you could do this:

function checkWindowSize() {
    var width = $(window).width();
    document.body.className = width > 1600 ? 'wLarge' :
                              width > 1440 ? 'w1680' :
                              width > 1280 ? 'w1440' :
                              width > 1024 ? 'w1280' : '';
}

Some people might advise you to do it with a switch statement, but then, some people also like to eat their young.

This function will overwrite the body's class every time it's called (the default, if the browser is smaller than/equal to 1024 pixels, is no class at all), so like I said it won't work if your body has other classes that need to be maintained.

EDIT Per Šime's suggestions, here's a safer way to do it:

function checkWindowSize() {
    var width = $(window).width(),
    new_class = width > 1600 ? 'wLarge' :
                width > 1440 ? 'w1680' :
                width > 1280 ? 'w1440' :
                width > 1024 ? 'w1280' : '';

    $(document.body).removeClass('wLarge w1680 w1440 w1280').addClass(new_class);
}

This worked for me thanks to Naina's comment here: https://www.quora.com/How-do-I-add-and-remove-CSS-classes-using-jQuery-based-on-the-screen-size

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        if($(window).width() < 768) {
           $("#myDiv").addClass("myClass");
           $("#otherDiv").removeClass("myClass");  
        }    
    });
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!