本文最后更新于:2024年12月29日 凌晨
两列高度不排列排列显示,常见于商品浏览设计。 原理是:
固定 n 列.
动态 存储 n 列 的高度 heighRecord
在第 n 个元素之后,动态的选择插入最小的列的高度,用 position:’absolute’,top 更改。
插入之后,更新当前列的高度,往后重复 步骤 3
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 <!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 > .container { width : 400px ; position : relative; display : flex; flex-wrap : wrap; } .box { width : 200px ; } </style > </head > <body > <div class ="container" > <div class ="box" style ="height: 200px; background-color: red" > 1</div > <div class ="box" style ="height: 700px; background-color: blue" > 2</div > <div class ="box" style ="height: 100px; background-color: black" > 3</div > <div class ="box" style ="height: 500px; background-color: gray" > 4</div > <div class ="box" style ="height: 100px; background-color: gray" > 5</div > </div > <script > const children = document .querySelectorAll (".box" ); const heighRecord = []; for (let i = 0 ; i < children.length ; i++) { if (i < 2 ) { heighRecord.push (children[i].offsetHeight ); } else { let minHeight = Math .min (...heighRecord); let minHeightIndex = heighRecord.indexOf (minHeight); children[i].style .position = "absolute" ; children[i].style .top = minHeight + "px" ; children[i].style .left = minHeightIndex * 200 + "px" ; heighRecord[minHeightIndex] += children[i].offsetHeight ; } } </script > </body > </html >
问题 1.
参考
现成库