我有一个相册。
HTML:
<div class="gallery">
<figure class="figure">
<img src="..." class="figure-img img-fluid gallery-item">
<figcaption class="figure-caption">...</figcaption>
</figure>
...
</div>
CSS:
.gallery {
column-width: 300px;
column-gap: 0;
}
.gallery-item {
width: 350px;
margin-bottom: 1rem;
display: inline-block;
padding: 0.3rem;
}
图片的个数不固定,高度可以不同。
我正在尝试以这种方式在 JQuery 中迭代数字:
var items = $('.gallery').children();
在这种情况下,迭代图片的顺序是垂直的。我的意思是,首先我从第一列开始从上到下获取图片,然后是完整的第二列,依此类推。我理解这是因为我的 HTML 中的数字顺序应该是垂直的。但我需要一种方法以这种方式迭代数字:
或许,有一种方法可以仅使用 JQuery 来完成。或者我应该对我的 HTML 和 CSS 进行一些更改。解决此问题的最佳方法是什么?
最佳答案
你必须在迭代之前对元素进行排序(纯 js 解决方案):
const items = [...document.querySelectorAll('.gallery figure')]
items.sort((a, b) => a.offsetTop/2 - b.offsetTop);
var output = ''
for ({textContent:t} of items) output += `${t} `
console.log(output)
.gallery {
display: flex;
flex-flow: column wrap;
height: 400px; width:500px;
}
figure {
width: 150px;
margin: 0 1rem 1rem 0;
background: #aaa;
color: #fff;
text-align: center;
font-size: 40px;
line-height: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
<figure style="height:100px">1</figure>
<figure style="height:80px">2</figure>
<figure style="height:120px">3</figure>
<figure style="height:70px">4</figure>
<figure style="height:100px">5</figure>
<figure style="height:100px">6</figure>
<figure style="height:80px">7</figure>
<figure style="height:120px">8</figure>
<figure style="height:70px">9</figure>
</div>
关于jquery - 如何在 JQuery 中迭代作为 div 中的列实现的图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459254/