gpt4 book ai didi

javascript - CSS/HTML 如何只显示 flexbox 的前两行

转载 作者:行者123 更新时间:2023-12-04 07:44:26 26 4
gpt4 key购买 nike

对于一个元素,我需要创建一个搜索栏。搜索结果需要显示在网格中。这些元素应该彼此相邻,两行高。如果有更多结果,我需要显示一个按钮 +32以显示所有结果。
我面临的问题是我不知道如何实现这一点。我使用了 flexbox 和 flex-wrap 以便在新元素不适合前一行时显示在下一行。但我不知道如何只显示前两行。
enter image description here

.container{
display: flex;
flex-wrap: wrap;
background-color: blue;
max-width: 15rem;
gap: 1rem;
}

.item{
background-color: red;
padding: 0 0.2rem;
}
<div class="container">
<div class="item">
<p>Hello</p>
</div>
<div class="item">
<p>Helllooo</p>
</div>
<div class="item">
<p>Hel</p>
</div>
<div class="item">
<p>Hello</p>
</div>
<div class="item">
<p>Test</p>
</div>
<div class="item">
<p>For</p>
</div>
<div class="item">
<p>Hello</p>
</div>
<div class="item">
<p>Hello</p>
</div>
<div class="item">
<p>Helllooo</p>
</div>
<div class="item">
<p>Hel</p>
</div>
<div class="item">
<p>Hello</p>
</div>
</div>

最佳答案

这是一个快速解决方案,尽管它还没有计算长度。

items = ["Helooo","Testing","Holaaaa","Hiiii","Hello","Greetings fine sir","Welcome","Bonjour","Oi you there"];

let limit = 5; // You will need to calculate this somehow

function display(limit){
document.getElementById("searchContainer").innerHTML = "";
for (let item of items.slice(0,limit)){
document.getElementById("searchContainer").innerHTML += `<div class=item>${item}</div>`;
}
if (items.length > limit){
document.getElementById("searchContainer").innerHTML += `<div class=item onclick="display(${items.length})">+${items.length-limit}</div>`;
}
}

display(limit);
.container{
display: flex;
flex-wrap: wrap;
background-color: whitesmoke;
max-width: 15rem;
gap: 1rem;
}

.item{
background-color: rgb(100,100,200);
padding: 0 0.2rem;
border-radius: 2px;
}
<div class=container id=searchContainer>
</div>

关于javascript - CSS/HTML 如何只显示 flexbox 的前两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67268346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com