我在頁面上有許多不同大小的元素,它們都具有相同的 .margin-top-auto 類
在頁面加載之前,我無法知道元素的高度。
我需要在頁面加載時向這些元素添加 {margin-top = 每個元素的高度}。
正在尋找可以為我完成此任務的 jQuery/Vanilla 代碼段。
非常感謝。
uj5u.com熱心網友回復:
你可以得到元素的offsetHeight:
const height = div.offsetHeight;
div.style.marginTop = height 'px'
console.log(height)
#div{
background-color:black;
height:100px;
width:100px;
}
<div id="div"></div>
要定位多個元素,您可以執行以下操作:
document.querySelectorAll('.margin-top-auto').forEach(e => e.style.marginTop = e.offsetHeight 'px')
.margin-top-auto{
height:100px;
width:100px;
background-color:black;
}
.row{
display:flex;
}
<div class="row">
<div class="margin-top-auto"></div>
<div class="margin-top-auto"></div>
<div class="margin-top-auto"></div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361819.html
標籤:javascript 查询
