javascript - 获取flex元素第一行的元素个数
问题描述
正如我在问题标题中所问的那样,有没有一种方法可以获取 flex 元素第一行中元素的数量?
下面是一张显示我的问题的图片。
我需要第一次换行之前的图片数量(在本例中为 5),因为我想更改整行(这里是 5 个元素,但屏幕更大可能是 7 个)。我怎样才能得到这个号码?我真的不知道,所以我希望你能帮助我。
如果您想查看代码,请在评论中告诉我。
谢谢
解决方案
根据@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>
推荐阅读
- git - Git 分支在后面,但在双重合并后包含相同的代码
- c# - Blazor azure AD 从图形 API 检索电子邮件
- django - 限制 django 频道连接
- php - 如何从 ks.cfg 文件 kickstart 在 RHEL 8 上从 remi 的 repo 安装 php rpm
- python - 从 jira 到 markdown 格式的 Python 正则表达式文本
- flutter - Erro Flutter VsCode 终端
- c# - 如何获取 UWP ListView 中文本和其他元素的像素位置?
- c - 考虑到硬件限制和使用限制的 IEEE 754 符合 sqrtf() 实现
- flutter - 使用简单代码时,无法将参数类型“JsObject”分配给参数类型“BuildContext”
- javascript - GSAP scrollTrigger - 仅动画被触发的元素