媒体查询通常较好。但是,如果我处于运行时有很多操作的单页应用程序中,我将使用onresize()来代替。 Javascript为您提供了更多的动态设置断点的自由(特别是如果您正在使用append()等东西移动DOM树内的元素时)。您有安装是非常接近我使用的一个:
function setWidthBreakpoints(windowWidth) {
if (windowWidth >= 1200) {
newWinWidth = 'lg';
} else if (windowWidth >= 992) {
newWinWidth = 'md';
} else if (windowWidth >= 768) {
newWinWidth = 'sm';
} else {
newWinWidth = 'xs';
}
}
window.onresize = function() {
setWidthBreakpoints($(this).width());
if (newWinWidth !== winWidth) {
onSizeChange();
winWidth = newWinWidth;
}
};
function onSizeChange() {
// do some size changing events here.
}
,你有没有包括在被认为是最佳做法的一件事是debouncing function,如保罗·爱尔兰下面提供的一个,这可防止重复resize事件的浏览器窗口中烧:
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this, args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
所以结合了去抖到您的调整大小功能,你应该是金色的。
CSS媒体查询似乎是一个更好的选择,这取决于你实际上在做什么? – adeneo 2015-02-23 17:50:31
我基本上是在移动设备上的主要内容之后移动左边栏,所以它出现在屏幕的底部而不是顶部。不确定这可以通过单独的媒体查询来实现吗? – pavsid 2015-02-23 17:55:25
我同意adeneo,我认为你应该使用媒体查询 – 2015-02-23 17:58:24