瀑布流加載是一種不錯的前端加載方式,用戶的體驗也還不錯。本次嘗試中涉及到佈局、圖片追加、滾動條監控的內容
主要實現步驟:計算獲取高度最低列,添加圖片到其下,定時器每次添加圖片,下拉加載問題
前端的佈局使用到了flex
彈性佈局
前端顯示圖片部分的HTML代碼:
<div class="gallary"> <!-- 第一列 --> <div class="imgBox" id="item1"> </div> <!-- 第二列 --> <div class="imgBox" id="item2"> </div> <!-- 第三列 --> <div class="imgBox" id="item3"> </div> <!-- 第四列 --> <div class="imgBox" id="item4"> </div> </div>
那麼在css中這樣設置即可:
.gallary{ width: 70%; margin: 8px auto; padding: 5px 8px; background-color: #fff; display: flex; /*設置felx佈局*/ flex-direction: row; /*方向是橫向(行)*/ } .imgBox{ flex: 1; /*佔比爲1,有四列佔比就是1/4*/ padding: 0px; margin:10px 5px; width: 250px; } .imgBox img{ width: 100%; margin:4px; transition: all 0.2s ease-in-out; /*淡入淡出*/ } .imgBox img:hover{ cursor: pointer; transform: scale(1.05); /*放大img*/ box-shadow: 1px 1px 2px #777; }
要想獲取最低高度的列,那麼就需要獲取每列的高度並取得最小列,返回其節點。
// 獲取最小的列 function getMinDiv(){ var it1 = $('#item1'); var it2 = $('#item2'); var it3 = $('#item3'); var it4 = $('#item4'); var it1Height = calHeight(it1.children()); var it2Height = calHeight(it2.children()); var it3Height = calHeight(it3.children()); var it4Height = calHeight(it4.children()); // 計算函數單獨寫 var minDiv = Math.min(it1Height, it2Height, it3Height, it4Height); if(minDiv == it1Height){ return it1; } else if(minDiv == it2Height){ return it2; } else if(minDiv == it3Height){ return it3; } else{ return it4; } } // 計算列圖片佔用高度 function calHeight(imgs){ if(imgs == null || imgs.length == 0 ){ return 0; } else{ var Height = 0; for (var i = 0; i < imgs.length; i++) { Height += imgs[i].height; } return Height; } }
添加圖片到對應列後:
// 插入圖片 function insertImgs(windowHeight){ var counter = 0; var inter = setInterval(function(){ // console.log(windowHeight < document.documentElement.scrollHeight); if( windowHeight < document.documentElement.scrollHeight || counter>10){ clearInterval(inter); //清除定時器 } var div = getMinDiv(); var num = Math.floor((Math.random()*10)+1); // 獲取img目錄下隨機10張圖片 div.append('<img src="./img/'+num+'.jpg">'); counter += 1; }, 100); }
文檔加載,同時監控滾動條高度,來決定是否加載新的圖片:
$(function(){ var windowHeight = window.screen.height+500; // 屏幕高度+500,初始化圖片加載佔用限制高度 var initHeight = windowHeight; var timer = null; // 節流,防止滾動條多次執行事件 insertImgs(windowHeight); //第一次加載 $(window).scroll(function(){ clearTimeout(timer); // 已經滾動高度 + 屏幕高度 > 能滾動高度 timer = setTimeout(function () { if($(document).scrollTop() + window.screen.height > document.documentElement.scrollHeight){ insertImgs(windowHeight+=window.screen.height); } }, 1000); }) })
打包給大家,有興趣的可以下載參考:
主要參考如下文章: