[英]Manipulating the DOM using jQuery .resize()
我想根據不同的瀏覽器大小更改DOM中元素的順序。
我已經研究過使用intention.js
但是覺得它可能對我需要的東西來說是過高的(取決於underscore.js
)。
因此,我正在考慮使用jQuery的.resize()
,但想知道您是否認為以下內容是否可以接受,並且符合最佳實踐...
var layout = 'desktop';
$( window ).resize(function() {
var ww = $( window ).width();
if(ww<=767 && layout !== 'mobile'){
layout = 'mobile';
// Do something here
}else if((ww>767 && ww<=1023) && layout !== 'tablet'){
layout = 'tablet';
// Do something here
}else if(ww>1023 && layout !== 'desktop'){
layout = 'desktop';
// Do something here
}
}).trigger('resize');
我將當前布局存儲在layout
變量中,以便僅在窗口進入下一個斷點時才觸發函數。
媒體查詢通常是首選。 但是,如果我處於一個在運行時具有很多操作的單頁應用程序中,我將改用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.
}
您尚未包括的被認為是最佳實踐的一件事是防彈跳功能 ,例如Paul Irish提供的以下功能 ,它可以防止在瀏覽器窗口中重復觸發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...
});
因此,在您的調整大小功能中加入一個去抖器,您應該會很聰明。
在實踐中最好使用媒體查詢
試試這個 ,我很忙,以后會重構。
SCSS:
body, html, .wrapper { width: 100%; height: 100% }
.sidebar { width: 20%; height: 500px; float: left;
&.mobile { display: none } }
.content { float: right; width: 80% }
.red { background-color: red }
.blue { background-color: blue }
.green { background-color: green }
@media all and (max-width: 700px) {
.content { width: 100%; float: left }
.sidebar { display: none
&.mobile { display: block; width: 100% }
}
}
HAML
.wrapper
.sidebar.blue
.content.red
.content.green
.sidebar.mobile.blue
在700像素的分頁符上,側邊欄消失,並且出現了移動側邊欄。 這樣可能會更優雅,但您會明白。
這種方法唯一可能的缺點是重復側邊欄。
就是這樣,沒有JS。
好的,我提出原始問題的原因是因為我找不到移動左側內容欄(在HTML的最前面出現)以使其出現在移動內容之后的方法。
盡管有評論,但我仍然看不到單獨使用媒體查詢和position
或display
如何可靠地解決問題(也許有人可以舉個例子嗎?)。
但是,這確實促使我研究了flexbox模型-display display: flex
,因此我最終使用了它,特別是flex的order
屬性來重新排列側邊欄和內容區域的順序。
此處的好指南-https: //css-tricks.com/snippets/css/a-guide-to-flexbox/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.