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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11047514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:07:13  来源:igfitidea点击:

jquery, add/remove class when window width changes

jquery

提问by Gillian

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 it is possible to reduce the lines of code.

我只是想知道是否有更好的方法来做到这一点,或者是否可以减少代码行数。

Basically I want to be able to alter the styles when the site is viewed on a smaller screen. I thought it would be best to add a new class to the html tag when it went under a certain width...

基本上,我希望能够在较小的屏幕上查看站点时更改样式。我认为最好在 html 标签下添加一个新类,当它低于一定宽度时......

Anyways here's my code.

无论如何,这是我的代码。

<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');}
 });

Thanks

谢谢

Gillian

阿娇

回答by Jared Farrish

Well, I know I'm late to the party, but I saw some things like $(document).ready()that weren't really necessary.

好吧,我知道我参加聚会迟到了,但我看到一些这样的事情$(document).ready()并不是真正必要的。

Try to cache your selectors if you're calling them over and over again, a la var $window = $(window);This will help with performance. I use a function expression to encapsulate to I stay out of the global scope but still have access to my $windowand $htmlcached jQuery selected elements.

如果您一遍又一遍地调用选择器,请尝试缓存它们,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);

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

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

Probably a little cleaner, little easier to follow:

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

(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);

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

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

回答by Raab

Use Media classes

使用媒体类

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

  }
}

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

  }
}

回答by iappwebdev

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);
    });
});

回答by Ananth

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

$(document).ready( function() {
    $(window).resize(resize);
    resize();
});

回答by user3778154

You Can also Use this Method I think its very clear to follow :

您也可以使用此方法,我认为遵循以下方法非常清楚:

$(window).on('resize', function(){
      var win = $(this);
      if (win.width() < 514) { 

      $('html').addClass('mobile');

      }
    else
    {
        $('html').removeClass('mobile');
    }

});

Simple Method

简单方法

回答by William Schroeder McKinley

This issue pestered me for a while, actually. I usually have multiple sizes for transitions. I wrote this an thought I'd share:

事实上,这个问题困扰了我一段时间。我通常有多种尺寸的过渡。我写了这个我想分享的想法:

$(function() {
  var pageTransitions = [['full',1600],['mobile',800],['tiny',400],['micro',0]]; // number shows minimum size - must be from high to low
  function resize() {
    var target = 0,
        w = $(window).width(),
        h = $('html');
    $.each(pageTransitions, function(index, pageTransition) {
        if( w > pageTransition[1]) {
            target = index;
            return false;
        }
    });
    $.each(pageTransitions, function(index, pageTransition) {
        h.removeClass(pageTransition[0]);
    });
    h.addClass(pageTransitions[target][0]);
  }
  resize();
  jQuery(window).on('resize', function() {
    resize();
  });
});

http://jsfiddle.net/mckinleymedia/ERZ3q/7/

http://jsfiddle.net/mckinleymedia/ERZ3q/7/

回答by Umar Tariq

Try this. It works for me

尝试这个。这个对我有用

function resize() {
        if ($(window).width() < 514) {}
        else {}
    }

    $(document).ready( function() {
        $(window).resize(resize);
        resize();
    });