jQuery,当窗口宽度更改时添加/删除类 [英] jquery, add/remove class when window width changes
问题描述
我写了一个非常基本的脚本,可以在加载时或在调整窗口大小时添加/删除类.
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.
基本上,我希望能够在较小的屏幕上查看网站时更改样式.我认为最好是在宽度小于一定宽度时向html标签添加一个新类...
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...
无论如何,这是我的代码.
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');}
});
谢谢
吉利安
推荐答案
好吧,我知道我参加晚会很晚,但是我看到了诸如$(document).ready()
之类的东西并不是真正必要的.
Well, I know I'm late to the party, but I saw some things like $(document).ready()
that weren't really necessary.
如果要一遍又一遍地调用选择器,请尝试对其进行缓存,请按var $window = $(window);
键,这将有助于提高性能.我使用函数表达式进行封装,以使其不属于全局范围,但仍可以访问我的$window
和$html
缓存的jQuery选定元素.
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 $window
and $html
cached jQuery selected elements.
(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
可能更清洁,更容易理解:
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
这篇关于jQuery,当窗口宽度更改时添加/删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!