用JS +ES6编写瀑布流
时间: 2024-01-15 13:05:32 浏览: 27
瀑布流(Waterfall Flow)是一种常见的网页布局方式,可以让页面中的元素像瀑布一样排列。下面是使用 JavaScript 和 ES6 实现瀑布流布局的示例代码:
HTML:
```html
<div class="waterfall-flow"></div>
```
CSS:
```css
.waterfall-flow {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.waterfall-flow .item {
width: 200px;
margin: 10px;
}
```
JavaScript:
```javascript
// 获取瀑布流容器
const waterfallFlow = document.querySelector('.waterfall-flow')
// 定义列数和每列的宽度
const columnCount = 4
const columnWidth = 200
// 定义数组存储每一列的高度
const columnHeights = new Array(columnCount).fill(0)
// 获取要排列的元素
const items = Array.from(waterfallFlow.querySelectorAll('.item'))
// 循环遍历每一个元素
items.forEach(item => {
// 获取元素高度
const itemHeight = item.offsetHeight
// 找到高度最短的那一列
const shortestColumnIndex = columnHeights.indexOf(Math.min(...columnHeights))
// 计算元素在当前列中的位置
const itemLeft = shortestColumnIndex * columnWidth
const itemTop = columnHeights[shortestColumnIndex]
// 设置元素的位置和样式
item.style.left = `${itemLeft}px`
item.style.top = `${itemTop}px`
item.style.position = 'absolute'
// 更新当前列的高度
columnHeights[shortestColumnIndex] += itemHeight + 10
})
// 设置容器高度为所有列中最高的高度
const tallestColumnHeight = Math.max(...columnHeights)
waterfallFlow.style.height = `${tallestColumnHeight}px`
```
这段代码的实现原理是,先定义瀑布流容器的列数和每一列的宽度,然后循环遍历瀑布流容器中的每一个元素,找到高度最短的那一列,计算元素在当前列中的位置,设置元素的位置和样式,更新当前列的高度,最后设置容器的高度为所有列中最高的高度。