1. 程式人生 > 實用技巧 >瀑布流以及分頁載入

瀑布流以及分頁載入

瀑布流又稱瀑布流式佈局,是比較流行的一種網站頁面佈局方式。視覺表現為參差不齊的多欄佈局,最早採用此佈局的是網站是 Pinterest,後逐漸在國內流行。
瀑布流效果
即多行等寬元素排列,後面的元素依次新增到其後,等寬不等高,根據圖片原比例縮放直至寬度達到我們的要求,依次按照規則放入指定位置

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /*
#content { width: 100px; height: 100px; background: red; position: absolute; } */ html, body { height: 100%; width: 100%; background-color:#cccccc; } #main { height: 800px; width:
100%; overflow-y: scroll; position: relative; } .obox { width: 200px; position: absolute; border:3px solid #ffffff; } </style> </head> <body> <!-- <div id="content"> </div> --> <div id="main"> </div> </body> <script type="text/javascript"> //
瀑布流 var arr = [];//定義一個數組,用來儲存元素的高度長度等於列數 let dom = document.getElementById('main') let cloumn = parseInt(dom.clientWidth / 200) var scrollIndex = 0 function reload(index) { for (let i = 0; i < 100; i++) { let domChild = document.createElement('div') domChild.setAttribute('class', 'obox') let height = Math.floor(Math.random() * 100) domChild.style.height = height + 'px' domChild.style.backgroundColor = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})` dom.appendChild(domChild) } } function change(scrollIndex) { let divChild = document.getElementsByClassName('obox') for (let j = scrollIndex * 100; j < divChild.length; j++) { if (j < cloumn) { divChild[j].style.left = (200 + 10) * j + 'px' divChild[j].style.top = 0 arr.push(divChild[j].offsetHeight); } else { let minIndex = Math.min.apply(null, arr);           //取到arr的最小值 var index = 0 for (var i = 0; i < arr.length; i++) { if (arr[i] == minIndex) { index = i } } divChild[j].style.top = arr[index] + 10 + 'px' divChild[j].style.left = divChild[index].offsetLeft + 'px' arr[index] = arr[index] + divChild[j].offsetHeight + 10 } } } window.onload = function () { reload(0) change(0) } //按需載入//分頁的形式也不是懶載入 dom.addEventListener('scroll', function () { let minIndex = Math.min.apply(null, arr); if ((dom.scrollTop + dom.clientHeight) - minIndex > 10) { scrollIndex++ reload(scrollIndex) change(scrollIndex) } }) </script> </html>