获取flex元素第一行的元素个数

Get the number of elements in the first row of a flex element

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

下图显示了我的问题。

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

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

谢谢

根据@AdilBimzagh 的评论

Get the width of the container and the width of one element, then divide the container's width by the element's width and you'll get the number of elements in each row, and don't forget to count the padding and margin of the element and the container.

主要功能是computeFirstRowItems。它的工作原理是将 flex-container 的宽度除以单个项目的 outerWidth。参见 difference between width and outerWidth here

// See also: 

// 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>