jquery,在窗口宽度改变时添加/删除类

Gil*_*ian 22 jquery

我写了一个非常基本的脚本来加载/删除一个类加载或调整窗口大小.

我只是想知道是否有更好的方法来做这个或者是否有可能减少代码行.

基本上我希望能够在较小的屏幕上查看网站时改变样式.我认为最好在html标签的某个宽度下添加一个新类...

不管怎样,这是我的代码.

<script type="text/javascript">
 $(document).ready( function() {
    /* Check width on page load*/
    if ( $(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {}
 });

 $(window).resize(function() {
    /*If browser resized, check width again */
    if ($(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {$('html').removeClass('mobile');}
 });
Run Code Online (Sandbox Code Playgroud)

谢谢

阿娇

Jar*_*ish 54

嗯,我知道我迟到了,但我看到一些类似的事情$(document).ready()并不是真的有必要.

如果你一遍又一遍地调用它们,请尝试缓存你的选择器,var $window = $(window);这将有助于提高性能.我使用函数表达式封装到我不在全局范围内,但仍然可以访问我$window$html缓存的jQuery选定元素.

(function($) {
    var $window = $(window),
        $html = $('html');

    $window.resize(function resize(){
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }).trigger('resize');
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/userdude/rzdGJ/1

可能更清洁,更容易遵循:

(function($) {
    var $window = $(window),
        $html = $('html');

    function resize() {
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }

    $window
        .resize(resize)
        .trigger('resize');
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/userdude/rzdGJ/2

  • 一个好的答案的例子:) (2认同)

Raa*_*aab 17

使用媒体类

@media screen and (max-width: 900px) {
  .class {
    width:800px;

  }
}

@media screen and (max-width: 500px) {
      .class {
        width:450px;

  }
}
Run Code Online (Sandbox Code Playgroud)


iap*_*dev 14

首先,使用函数DRY(不要重复自己)代码:

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);
    });
});
Run Code Online (Sandbox Code Playgroud)


Ana*_*nth 5

function resize() {
    if ($(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {$('html').removeClass('mobile');}
}

$(document).ready( function() {
    $(window).resize(resize);
    resize();
});
Run Code Online (Sandbox Code Playgroud)