原生js实现简易瀑布流 #137
Anuluca Date : 2021-07-13 Tags : 3
需求
使用原生 js 实现,从左到右,由上至下见缝插针,列数适应页面。
实现前的基础代码
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
| <style> * { margin: 0; padding: 0; } .box > img { width: 400px; margin: 10px; } .box { float: left; } </style> <body> <div class="outer-box"> <div class="box"> <div>1</div> <img data-src="./1.jpg" /> </div> <div class="box"> <div>2</div> <img data-src="./2.jpg" /> </div> <div class="box"> <div>3</div> <img data-src="./3.jpg" /> </div> <div class="box"> <div>4</div> <img data-src="./4.jpg" /> </div> <div class="box"> <div>5</div> <img data-src="./5.jpg" /> </div> <div class="box"> <div>6</div> <img data-src="./6.jpg" /> </div> <div class="box"> <div>7</div> <img data-src="./7.jpg" /> </div> <div class="box"> <div>8</div> <img data-src="./8.jpg" /> </div> <div class="box"> <div>9</div> <img data-src="./9.jpg" /> </div> <div class="box"> <div>10</div> <img data-src="./10.jpg" /> </div> <div class="box"> <div>11</div> <img data-src="./11.jpg" /> </div> <div class="box"> <div>12</div> <img data-src="./12.jpg" /> </div> <div class="box"> <div>13</div> <img data-src="./13.jpg" /> </div> </div> </body>
|
实现代码
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
| <script> function waterfall() { let box = document.getElementsByClassName("box"); let screenWidth = document.body.clientWidth; let boxWidth = box[0].clientWidth; var heightArr = []; let cols = parseInt(screenWidth / boxWidth);
[...box].forEach((element, index) => { let boxHeight = element.offsetHeight; if (index < cols) { heightArr[index] = boxHeight; } else { let minHeight = Math.min(...heightArr); let minIndex = heightArr.indexOf(minHeight); document .getElementsByClassName("box") [index].setAttribute( "style", `position:absolute;left:${minIndex * boxWidth}px;top:${minHeight}px` ); heightArr[minIndex] += boxHeight; } }); console.log(heightArr); }
setTimeout(() => { waterfall(); }, 1000); </script>
|