瀑布流效果js實現
阿新 • • 發佈:2020-07-25
瀑布流js實現
1 // 頁面尺寸改變時實時觸發 2 window.onresize = function() { 3 //重新定義瀑布流 4 waterFall(); 5 }; 6 7 //初始化 8 window.onload = function(){ 9 console.log("開始瀑布流") 10 //實現瀑布流 11 waterFall(); 12 13 } 14 15 function waterFall(){ 16 //1.求出列數 17 var box = $(".item"); 18 var boxWidth = box.outerWidth(); //當前圖片的寬度 不用width是因為width會使圖片緊挨著左右沒有間隙,而outerWidth會在圖片寬度基礎上加上padding以致每張圖片左右有一定的間隙20 var screenWidth = $(window).width(); //整個螢幕的寬度 21 var cols = parseInt(screenWidth/boxWidth); //列數23 //2.建立陣列 24 var heightArr = []; 25 //3.圖片遍歷迴圈,除第一排不需要定位,取高度值 其他排 定位處理 26 $.each(box,function(index,item){27 //取出圖片的高度29 var boxHeight = $(item).outerHeight(); 30 if(index < cols){ //第一排,取高度值32 heightArr[index] = boxHeight; 33 }else{ 34 //最小圖片的高度 35 //陣列中最小的值 36 var minBoxHeight = Math.min(...heightArr); //第一列圖片高度值存放在陣列中heightArr,找出最小值37 //最小的索引 38 var minBoxIndex = $.inArray(minBoxHeight,heightArr); //遍歷陣列heightArr中查詢minBoxHeight這個最小值,返回下標。 39 $(item).css({ 40 position:'absolute', 41 left:minBoxIndex*boxWidth+'px', 42 top:minBoxHeight+'px' 43 }); 44 //高度追加 45 heightArr[minBoxIndex] += boxHeight; 46 } 47 }) 48 }