1 回答

TA貢獻1725條經驗 獲得超8個贊
您遇到此錯誤是因為 和 等元素<p>
默認<div>
會擴展父級的整個寬度。你應該用width: fit-content
它來阻止它。
div {
background-color: blue;
}
p {
background-color: red;
}
.width {
width: fit-content;
}
<div>This is a DIV with width: auto</div>
<p>This is a P with width: auto</p>
<div class="width">This is a DIV with width: fit-content</div>
<p class="width">This is a P with width: fit-content</p>
clientHeight
將返回整個窗口的高度。您應該只關注要渲染的元素的父元素,以獲得更好的閱讀效果。使用offsetWidth
和offsetHeight
來獲取父級的完整寬度。
var div = document.getElementById('div');
div.innerHTML = 'Width: ' + div.offsetWidth + '<br>Height: ' + div.offsetHeight;
.square {
width: 100px;
height: 100px;
background-color: blue;
}
<div id="div" class="square"></div>
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報