前端实现js实现瀑布图代码
时间: 2023-05-14 14:05:19 浏览: 120
以下是使用纯 JavaScript 实现瀑布图的示例代码:
HTML 代码:
```html
<div id="waterfall"></div>
```
CSS 代码:
```css
#waterfall {
display: flex;
flex-wrap: wrap;
margin: 0 -10px;
}
.item {
width: calc(33.33% - 20px);
margin: 10px;
position: relative;
}
.item img {
display: block;
width: 100%;
}
.item .caption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 10px;
font-size: 14px;
text-align: center;
}
```
JavaScript 代码:
```javascript
// 图片数据,格式为 { src: string, caption: string }
const images = [
{ src: 'image1.jpg', caption: 'Image 1' },
{ src: 'image2.jpg', caption: 'Image 2' },
{ src: 'image3.jpg', caption: 'Image 3' },
{ src: 'image4.jpg', caption: 'Image 4' },
{ src: 'image5.jpg', caption: 'Image 5' },
{ src: 'image6.jpg', caption: 'Image 6' },
{ src: 'image7.jpg', caption: 'Image 7' },
{ src: 'image8.jpg', caption: 'Image 8' },
{ src: 'image9.jpg', caption: 'Image 9' },
];
// 记录每列的高度
const colHeights = [0, 0, 0];
// 获取最短列的索引
function getShortestColIndex() {
let shortestColIndex = 0;
for (let i = 1; i < colHeights.length; i++) {
if (colHeights[i] < colHeights[shortestColIndex]) {
shortestColIndex = i;
}
}
return shortestColIndex;
}
// 创建图片元素
function createImageEl(image) {
const itemEl = document.createElement('div');
itemEl.classList.add('item');
const imgEl = document.createElement('img');
imgEl.src = image.src;
itemEl.appendChild(imgEl);
const captionEl = document.createElement('div');
captionEl.classList.add('caption');
captionEl.textContent = image.caption;
itemEl.appendChild(captionEl);
return itemEl;
}
// 初始化瀑布流布局
function initWaterfall() {
const waterfallEl = document.getElementById('waterfall');
for (const image of images) {
const itemEl = createImageEl(image);
const shortestColIndex = getShortestColIndex();
itemEl.style.order = shortestColIndex;
itemEl.style.top = colHeights[shortestColIndex] + 'px';
colHeights[shortestColIndex] += itemEl.offsetHeight + 20;
waterfallEl.appendChild(itemEl);
}
}
// 在窗口大小改变时重新布局瀑布流
function handleWindowResize() {
const waterfallEl = document.getElementById('waterfall');
for (const itemEl of waterfallEl.children) {
const shortestColIndex = getShortestColIndex();
itemEl.style.order = shortestColIndex;
itemEl.style.top = colHeights[shortest
阅读全文