javascript - CSS / HTML如何只显示flexbox的前两行
问题描述
对于一个项目,我需要创建一个搜索栏。搜索结果需要显示在网格中。这些项目应该彼此相邻并且两行高。如果有更多结果,我需要显示一个按钮+32
来显示所有结果。
我面临的问题是我不知道如何做到这一点。我使用了 flexbox 和 flex-wrap 以便在新项目不适合上一行时显示在下一行。但我不知道如何只显示前两行。
.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>
推荐阅读
- c# - 有没有办法让 Dns.GetHostEntry() 在 C Sharp 中强制使用 TCP 而不是 UDP?
- javascript - 在 Mongoose 和 Node.js 中按数值搜索
- python - 最小化“Ax−b”(如何编写函数与 scipy.optimize.fmin() 一起使用)
- mysql - auto_increment jumps by 3 and not 1
- vb.net - How to protect my file from sending to skype or upload to cPanel
- javascript - 如何使用此屏幕上的导航选项?
- java - Cucumber 即使设计了正确的 Stepdefinition 也无法找到 Step Definition
- php - 在 php codeigniter 中集成 react fuse 模板的最佳方法
- pentaho - 如何使用 pentaho 删除字符串中的重音符号/变音符号?
- c++ - 尝试用 C++ 编写我的第一个游戏,并收到语法错误:: 标识符消息