jquery - 如何在 JQuery 中迭代作为 div 中的列实现的图片?

标签 jquery html css

我有一个相册。

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 中的数字顺序应该是垂直的。但我需要一种方法以这种方式迭代数字:

enter image description here

或许,有一种方法可以仅使用 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/

相关文章:

javascript - 如何降低此 jquery 计数器动画的速度

jquery - 如何在使用表单向导时运行 jquery validate()?

javascript - 表单克隆唯一标识

html - nth-of-type 或 nth-child 在 chrome 上的工作不同?

jquery - 在 Internet Explorer 11 中,悬停下拉菜单在选择之前关闭

javascript - 有没有办法在顶部显示日历的月份名称?

javascript - 整数转字符串,如何修复以下错误: "TypeError: Can' t convert undefined to object"?

javascript - 如何使用一个 XSLT 文件中的变量到另一个 XSLT 文件

javascript - 单击选定文本后,窗口选择未提供更新范围

css - 在不使用只读的情况下更改禁用的文本框字体颜色