我有一個沒有高度的 div,每當我添加專案時,div 的高度就會增加。但是我想將最大高度限制為 5 個子 div。有時 item 有一兩行文本,應該被視為一個 item。當出現第 6 項時,滾動條應出現在 div 中,并且 div 的高度應調整為內部 5 項。
.box {
border: 1px solid black;
display: inline-block;
width: 150px;
}
<div class="box">
<p class="item">
1 test
</p>
<p class="item">
2test test test test test test
</p>
<p class="item">
3test
</p>
<p class="item">
4test
</p>
<p class="item">
5 test
</p>
<p class="item">
6 test
</p>
</div>
uj5u.com熱心網友回復:
僅根據給出的資訊,您可以回圈遍歷前 5 個專案并使用該getComputedStyle()方法獲取它們的高度。
邊距折疊有一些奇怪的行為,這可能會導致問題,具體取決于您實作此代碼的方式。但是,根據提供的示例,這可以按預期作業。
const box = document.querySelector(".box")
let maxHeight = 0
document.querySelectorAll(".item").forEach((item, index) => {
if(index < 5) maxHeight = parseFloat(getComputedStyle(item).getPropertyValue('height')) parseFloat(getComputedStyle(item).getPropertyValue('margin-top'))
})
box.style.maxHeight = `${maxHeight}px`
.box {
border: 1px solid black;
display: inline-block;
width: 150px;
overflow: auto;
}
<div class="box">
<p class="item">1 test</p>
<p class="item">2test test test test test test</p>
<p class="item">3test</p>
<p class="item">4test</p>
<p class="item">5 test</p>
<p class="item">6 test</p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527389.html
上一篇:如何在右側添加填充
下一篇:div定位在另一個行內的正下方
