jquery,在窗口宽度改变时添加/删除类
我写了一个非常基本的脚本来加载/删除一个类加载或调整窗口大小。
我只是想知道是否有更好的方法来做到这一点,或者是否有可能减少代码行。
基本上我希望能够在较小的屏幕上查看网站时改变样式。 我认为最好在html标签的某个宽度下添加一个新类…
不管怎样,这是我的代码。
$(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()
这样的东西,这些都不是必需的。
如果你一遍又一遍地调用它们,请尝试缓存你的选择器,la 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
可能更清洁,更容易遵循:
(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);
使用媒体类
@media screen and (max-width: 900px) { .class { width:800px; } } @media screen and (max-width: 500px) { .class { width:450px; } }
首先,使用函数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); }); });
function resize() { if ($(window).width() < 514) { $('html').addClass('mobile'); } else {$('html').removeClass('mobile');} } $(document).ready( function() { $(window).resize(resize); resize(); });
您也可以使用此方法我认为非常清楚:
$(window).on('resize', function(){ var win = $(this); if (win.width() < 514) { $('html').addClass('mobile'); } else { $('html').removeClass('mobile'); } });
简单的方法
实际上,这个问题困扰了我一段时间。 我通常有多种尺寸的过渡。 我写了一个我想分享的想法:
$(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(); }); });
试试这个。 这个对我有用
function resize() { if ($(window).width() < 514) {} else {} } $(document).ready( function() { $(window).resize(resize); resize(); });