什么是瀑布流布局?
先來看個瀑布流布局的網(wǎng)站實例
瀑布流布局
從上面的網(wǎng)站中可以看出,瀑布流布局就是這種錯落式的布局方式。它有一個特點,整個布局以列為單位,下一個區(qū)塊總是放在總高度最短的那一列的下面。
實現(xiàn)
整體思路:通過js找出一行中高度最短的那列,然后通過絕對定位將區(qū)塊放在那列的下方
step1
- 先顯示很多不同高度的img,寬度可以不同,反正到時候都是設置成統(tǒng)一寬度的
-
http://via.placeholder.com/100x100接口可以用來模擬一張圖片,100x100即圖片的寬和高,通過設置不同的高度獲取到很多圖片
正常連續(xù)多張圖片的顯示
step2
- 將圖片的position設置成absolute
.waterfall{
position: relative;
}
.waterfall img{
width: 100px;
margin: 10px;
position: absolute;
}
- 編寫js控制圖片位置
//獲取圖片的寬度
var imgWidth = $('.waterfall img').outerWidth(true)
//列數(shù) = 外層容器寬度 / 圖片寬度
var colCnt = Math.floor($('.waterfall').width() / imgWidth)
//定義一個存放每列列高的數(shù)組
var colHeight = []
//根據(jù)列數(shù)初始化數(shù)組
for(var i=0; i<colCnt; i++){
colHeight[i] = 0
}
//獲取數(shù)組中最小值下標
var minIndex = colHeight.indexOf(Math.min.apply(null, colHeight))
//對于每個img找到數(shù)組中列高最小的位置進行絕對定位
$('.waterfall img').each(function(){
$(this).css({
left: minIndex * imgWidth,
top: colHeight[minIndex]
})
colHeight[minIndex] += $(this).outerHeight(true)
minIndex = colHeight.indexOf(Math.min.apply(null, colHeight))
})
注:
① outerWidth()方法返回第一個匹配元素的外部寬度,該方法包含padding和border
如需包含margin,使用outerWidth(true),這樣在css中設置的圖片的margin會被計算在內(nèi),從而顯示有間隔的效果。
整體效果
step3
step2已經(jīng)實現(xiàn)了瀑布流布局,可是還是不夠完善,變動頁面的寬度,瀑布流布局并不能跟著變化,相當于根據(jù)初始頁面的寬度進行了一次性布局。下面增加實現(xiàn)瀑布流布局跟著寬度變化
js代碼改成如下
//獲取圖片寬度
var imgWidth = $('.waterfall img').outerWidth(true)
//列數(shù) = 外層容器寬度 / 圖片寬度
var colCnt = Math.floor($('.waterfall').width() / imgWidth)
//定義一個存放每列列高的數(shù)組
var colHeight = []
function waterfall(colCount){
//根據(jù)列數(shù)初始化數(shù)組
for(var i=0; i<colCount; i++){
colHeight[i] = 0
}
//獲取數(shù)組中最小值下標
var minIndex = colHeight.indexOf(Math.min.apply(null, colHeight))
//對于每個img找到數(shù)組中列高最小的位置進行絕對定位
$('.waterfall img').each(function(){
$(this).css({
left: minIndex * imgWidth,
top: colHeight[minIndex]
})
colHeight[minIndex] += $(this).outerHeight(true)
console.log('colHeight', colHeight)
minIndex = colHeight.indexOf(Math.min.apply(null, colHeight))
console.log('minIndex',minIndex)
})
}
//首次布局等到圖片到來在執(zhí)行
$('.waterfall img').on('load', function(){
waterfall(colCnt)
})
//resize頁面重新布局
$(window).on('resize', function(){
imgWidth = $('.waterfall img').outerWidth(true)
colCnt = Math.floor($('.waterfall').width() / imgWidth)
waterfall(colCnt)
})
注:在img的css中加入transition可以實現(xiàn)resize頁面瀑布流布局變化的動畫效果
最終效果
最終頁面展示