jquery, add/remove class when window width changes

前端 未结 7 1177
予麋鹿
予麋鹿 2020-11-27 13:26

I\'ve written out a very basic script to add/remove a class on load or when a window is resized.

I was just wondering if there was a better way of doing this or if i

相关标签:
7条回答
  • 2020-11-27 13:55

    First of all, DRY (Don't Repeat Yourself) your code by using a function:

    function checkWidth(init)
    {
        /*If browser resized, check width again */
        if ($(window).width() < 514) {
            $('html').addClass('mobile');
        }
        else {
            if (!init) {
                $('html').removeClass('mobile');
            }
        }
    }
    
    $(document).ready(function() {
        checkWidth(true);
    
        $(window).resize(function() {
            checkWidth(false);
        });
    });
    
    0 讨论(0)
提交回复
热议问题