瀑布流
- 原理:
1 每個元素的width
相等,height
不等;就像瀑布,水柱大小一樣,長短各異。
2 所有元素用position:absolute
定位,通過設置left & top
來擺放;
3 每次擺放在最短的一列
- 核心:
1 列從哪里來的?
var nodeWidth = $('.item').outerWidth(true), 1得到元素寬度
colNum = Math.floor( $(window).width()/nodeWidth ), 2窗口寬度/元素寬度= 隊列數
sumHeight = []; 3新建空數組
for(var i =0;i<colNum;i++){ 4遍歷隊列,填入數組:
sumHeight.push(0) 長度 = 隊列數
} 數值 = 每列所有元素高度總和
初始值 = 0
2 如何得到最短列?
$('.item').each(function(){
var idx = 0, 1假設最短列下標=0
minSumHeight = sumHeight[0];
for(var i=0;i<sumHeight.length;i++){ 2遍歷數組,得到最小數i
if(sumHeight[i]<minSumHeight){
idx = i; 3賦值給最短列
minSumHeight = sumHeight[i]
} 最短列 = 最小數
}
})
3 如何放入最短列?
$(this).css({ 通過position定位,設置:
'left':idxnodeWidth, left = 元素寬度最短列索引
'top':minSumHeight top = 最短列高度
});
重新計算最短列的值 : 把當前元素高度計入最短列
sumHeight[idx] += $(this).outerHeight(true);
- 問題
1 窗口變動,寬度更改怎么辦?
$(window).on('resize',function(){ 添加resize事件
render(); 執行上述render過程
})
2 如何封裝?
var water = ({ function render(){ 1把匿名函數賦給water
...... 2將上述render過程變成閉包
return{ 3留下接口
init:render
}
})()
water.init() 4調用water,執行render
木桶
原理:
每個元素的height
相等,width
不等;
就像木桶,每行高度近似,寬度完全相等;*2
行內所有木塊的高度完全相等,寬度不等。*1
過程:
1 獲得圖片:拿到資源(一些圖片地址)
2 加載圖片:使幾張圖片先成為同一高度(確保圖片不會變形) *1 首次縮放
2 預先擺放:從左到右,直到擺不下(根據寬度確定本行圖片數量)
3 正式擺放:把本行的幾張圖片放滿此行(保證每行寬度一致) *2 再次縮放
核心:
兩次縮放
1 首次縮放:如何等比縮放圖片?(以預設高為基準)
計算圖片寬高比 ratio = img.width / img.height
高度設為基礎行高 img.height = baseHeight
得到圖片基礎寬度 img.width = baseHeightratio
2 再次縮放:確定此行圖片數量之后,如何撐滿?(以容器寬為基準)
把這幾張高度一致的圖片所組成的行(row)整體縮放,使其寬度 = 行寬 , 得到新行高
newRowHeight = clientWidth rowheight/rowWidth;-
問題:
1 如何判斷這張圖片是否擺不下?
this.rowList.push(imgInfo); 放入圖片
for(var i=0; i< this.rowList.length; i++){ 每加入一張圖片
rowWidth = rowWidth + this.rowList[i].width; 重新計算這一行多張圖片總寬度
}
if(rowWidth > clientWidth){ 如果圖片總寬度大于容器寬度
this.rowList.pop(); 說明放不下,要拿出來!!this.layout(newRowHeight); 得到圖片,放入此行 this.rowList = []; 清空木板,開始擺放下行 this.rowList.push(imgInfo); 把剛才放不下的圖片擺進來 }
2 如何把圖片放入此行?
console.log('createRow');
var $rowCt = $('<div class="img-row"></div>'); 在頁面上創建行
$.each(this.rowList, function(idx, imgInfo){
var $imgCt = $('<div class="img-box"></div>'), 創建圖片容器
$img = $(imgInfo.target); 把此圖變成Jq對象,以便操作
$img.height(newRowHeight); 設置此圖高度 = 新行高
$imgCt.append($img); 把圖片放入容器
$rowCt.append($imgCt); 把容器放入行
});
this.$ct.append($rowCt); 把行放入頁面