主要思路如下
1.計(jì)算頁(yè)面的寬度铸磅,計(jì)算出頁(yè)面可放數(shù)據(jù)塊的列數(shù)刁赦。
2.將各個(gè)數(shù)據(jù)塊的高度尺寸記入數(shù)組中
3.用絕對(duì)定位先將頁(yè)面第一行填滿隔缀,因?yàn)榈谝恍械膖op位置都是一樣的幔妨,然后用數(shù)組記錄每一列的總高度鹦赎。
4.繼續(xù)用絕對(duì)定位將其他數(shù)據(jù)塊定位在最短的一列的位置之后然后更新該列的高度。
5.當(dāng)瀏覽器窗口大小改變時(shí)陶冷,重新執(zhí)行一次上面1-4步以重新排放(列數(shù)隨頁(yè)面寬度而改變钙姊,因而需要重新排放)毯辅。
6.滾動(dòng)條滾動(dòng)到底部時(shí)加載新的數(shù)據(jù)進(jìn)來(lái)后也是定位在最短的一列的位置之后然后更新該列的高度埂伦。
預(yù)覽:
https://jirengu-inc.github.io/jrg-renwu8/homework/%E5%BC%A0%E8%BD%A9/renwu30.html
源碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>renwu30</title>
<script src='//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
<style>
.water{
width: 300px;
margin: 5px;
position: absolute;
transition: all 1s;
}
.blue{
background-color: blue;
height: 300px;
}
.green{
background-color: green;
height: 400px;
}
.grey{
background-color: grey;
height: 700px;
}
.red{
background-color: red;
height: 450px;
}
.yellow{
background-color: yellow;
height: 250px;
}
</style>
</head>
<body>
<div class="water yellow"></div>
<div class="water blue"></div>
<div class="water grey"></div>
<div class="water yellow"></div>
<div class="water green"></div>
<div class="water red"></div>
<div class="water blue"></div>
<div class="water yellow"></div>
<div class="water red"></div>
<div class="water yellow"></div>
<div class="water red"></div>
<div class="water green"></div>
<div class="water blue"></div>
<div class="water grey"></div>
<div class="water blue"></div>
<div class="water yellow"></div>
<div class="water blue"></div>
<div class="water green"></div>
<div class="water red"></div>
<div class="water green"></div>
</body>
<script>
var zhangxuan=(function(){
function init(f, s){ //傳入?yún)?shù)f:父容器,s:瀑布節(jié)點(diǎn)
var $nodeW=s.outerWidth(true),
$winW=f.width(),
$nodeNum=parseInt($winW/$nodeW),
nodesSumHeight=[];
for(var i=0;i<$nodeNum;i++){
nodesSumHeight.push(0);
}
s.each(function(){ //這邊是遍歷所選節(jié)點(diǎn)思恐,注意內(nèi)部修改節(jié)點(diǎn)css需要用this
var $el=$(this),
$nodeH=$el.outerHeight(true),
temp=getmin(nodesSumHeight);
$el.css({
left:$nodeW*temp.idx,
top:temp.min
})
nodesSumHeight[temp.idx]+= $nodeH //把this的高度加入數(shù)組中
})
}
function getmin(arr){ //用來(lái)node高度數(shù)組中return最小值和下標(biāo)
var idx=0,
minSumHeight=arr[0];
for(var i=0;i<arr.length;i++){
if(arr[i]< minSumHeight){
idx=i;
minSumHeight= arr[i];
}
}
return{idx:idx, min:minSumHeight}
}
$(window).on('resize', function(){
init($(window), $('.water'))
})
return {
init:init
}
})()
zhangxuan.init($(window), $('.water'));
</script>
</html>