前端实现js实现瀑布图代码
时间: 2023-06-23 10:09:14 浏览: 93
利用JS实现简单的瀑布流加载图片效果
以下是一个简单的 JavaScript 实现瀑布图的代码:
HTML 代码:
```html
<div id="waterfall">
<div class="item">
<img src="image1.jpg">
<div class="caption">Image 1</div>
</div>
<div class="item">
<img src="image2.jpg">
<div class="caption">Image 2</div>
</div>
<div class="item">
<img src="image3.jpg">
<div class="caption">Image 3</div>
</div>
<div class="item">
<img src="image4.jpg">
<div class="caption">Image 4</div>
</div>
<div class="item">
<img src="image5.jpg">
<div class="caption">Image 5</div>
</div>
</div>
```
CSS 代码:
```css
#waterfall {
column-count: 3;
column-gap: 20px;
}
.item {
display: inline-block;
width: 100%;
margin-bottom: 20px;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
overflow: hidden;
position: relative;
}
.item img {
width: 100%;
height: auto;
display: block;
}
.item .caption {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 14px;
text-align: center;
}
```
JavaScript 代码:
```javascript
var waterfall = document.getElementById('waterfall');
var items = waterfall.getElementsByClassName('item');
var columns = [];
function setColumnHeight() {
var columnHeights = [];
for (var i = 0; i < columns.length; i++) {
columnHeights.push(columns[i].offsetHeight);
}
var minHeight = Math.min.apply(null, columnHeights);
for (var i = 0; i < columns.length; i++) {
columns[i].style.height = minHeight + 'px';
}
}
function createColumns() {
for (var i = 0; i < 3; i++) {
var column = document.createElement('div');
column.className = 'column';
waterfall.appendChild(column);
columns.push(column);
}
}
function arrangeItems() {
for (var i = 0; i < items.length; i++) {
var column = columns[i % 3];
column.appendChild(items[i]);
}
}
createColumns();
arrangeItems();
setColumnHeight();
window.addEventListener('resize', function() {
setColumnHeight();
});
```
这段代码使用了 CSS3 的 column-count 属性来实现列布局,JavaScript 代码则负责调整每一列的高度以保证水平线对齐。
阅读全文