1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| <!DOCTYPE html> <html> <head> <title>Js瀑布流布局</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1" /> <style type="text/css"> #container{ position: relative; } .item{ position: absolute; display: flex; justify-content: center; align-items: center; color: #fff; } </style> </head> <body> <div id="container"></div> </body> <script type="text/javascript"> var column = 3; var counter = 0; var columnHeight = Array(column).fill(0); var container = document.getElementById("container"); var colorList = ["#EAA78C", "#F9CD82", "#9ADEAD", "#9CB6E9", "#E49D9B", "#97D7D7", "#ABA0CA", "#9F8BEC","#ACA4D5", "#6495ED", "#7BCDA5", "#76B4EF","#E1C38F","#F6C46A","#B19ED1","#F09B98","#87CECB","#D1A495","#89D196","#FE9E9F", "#93BAFF", "#D999F9", "#81C784", "#FFCA62", "#FFA477"]; function random(min=0, max=1) { return min + ~~((max-min)*Math.random()) }
function findMinColumn(arr){ var min = arr[0]; var index = 0; arr.forEach((v,i) => { if(v < min) { min = v; index = i; } }) return [index,min]; }
function appendImg(){ var gap = 3; for(let i=0;i<12;++i){ var unit = { height:random(100,500), width: 300, color: colorList[random(0,colorList.length)] } var [minIndex,min] = findMinColumn(columnHeight); var d = document.createElement("div"); d.className = "item"; d.style.background = unit.color; d.style.height = `${unit.height}px`; d.style.width = `${unit.width}px`; d.style.top = `${min + gap}px`; d.style.left = `${(300 + gap) * minIndex}px`; d.innerText = `${++counter}#${unit.height}X${unit.width}`; columnHeight[minIndex] += (unit.height+gap); container.appendChild(d); } }
function init(){ appendImg(); var endLoad = columnHeight.some(v => v > window.innerHeight); if(!endLoad) init(); }
(function(){ init(); })();
window.onscroll = function (){ var marginBottom = 0; if (document.documentElement.scrollTop){ var scrollHeight = document.documentElement.scrollHeight; var scrollTop = document.documentElement.scrollTop + document.body.scrollTop; var clientHeight = document.documentElement.clientHeight; marginBottom= scrollHeight - scrollTop - clientHeight; } else { var scrollHeight = document.body.scrollHeight; var scrollTop = document.body.scrollTop; var clientHeight = document.body.clientHeight; marginBottom= scrollHeight - scrollTop - clientHeight; } if(marginBottom<=0) appendImg(); }
</script> </html>
|