首页 > 解决方案 > 获取flex元素第一行的元素个数

问题描述

正如我在问题标题中所问的那样,有没有一种方法可以获取 flex 元素第一行中元素的数量?

下面是一张显示我的问题的图片。

我需要第一次换行之前的图片数量(在本例中为 5),因为我想更改整行(这里是 5 个元素,但屏幕更大可能是 7 个)。我怎样才能得到这个号码?我真的不知道,所以我希望你能帮助我。

如果您想查看代码,请在评论中告诉我。

谢谢

标签: javascripthtmlcsslayoutflexbox

解决方案


根据@AdilBimzagh 的评论

获取容器的宽度和一个元素的宽度,然后将容器的宽度除以元素的宽度,就可以得到每一行的元素个数,别忘了计算元素的内边距和外边距容器。

主要功能是computeFirstRowItems。它通过将 flex-container 的宽度除以单个项目的 outerWidth 来工作。在此处查看width 和 outerWidth 之间的区别

// See also: https://stackoverflow.com/questions/17845027/what-is-difference-between-width-innerwidth-and-outerwidth-height-innerheight#17845094

// from http://youmightnotneedjquery.com/?ref=codebldr#outer_width_with_margin
function outerWidthMargin(el) {
  var width = el.offsetWidth;
  var style = getComputedStyle(el);

  width += parseInt(style.marginLeft) + parseInt(style.marginRight);
  return width;
}

// http://youmightnotneedjquery.com/?ref=codebldr#get_width
function width (el) {
  return parseFloat(getComputedStyle(el, null).width.replace("px", ""))
}

function computeFirstRowItems () {
  const ul = document.querySelector(".entry:first-child ul.img-list")
  const li = document.querySelector(".entry:first-child ul.img-list > li")

  return Math.floor(width(ul) / outerWidthMargin(li));
}

window.addEventListener("load", () => {
  console.log(computeFirstRowItems());
});
.img-list {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
}

.img-list > li {
  width: 25vw;
  list-style-type: none;
  background-color: steelblue;
  height: 25vh;
  margin: 0.7em 0;
}
<div class="entry">
  <ul class="img-list">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
 </div>
<div class="entry">
  <ul class="img-list">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul> 
</div>


推荐阅读