javascript獲取元素高度和寬度的方式 - cientHeight、offsetHeight、getComputedStyle、getBounding

javascript獲取元素高度能夠經過這幾種方式獲取:cientHeight、offsetHeight、getComputedStyle、getBoundingClientRectjavascript

clientHeight 獲取的元素高度包括內邊距。若是元素是 display: inline; 那麼獲得的結果是 0 。
offsetHeight 獲取元素的高度,包括內邊距和邊框的寬度。若是元素是 display: inline; 那麼獲得的結果是 0 。
getComputedStyle Window.getComputedStyle()方法返回一個對象,是這個元素的css屬性值。
例如:下面樣式代碼中,Window.getComputedStyle(document.getElementById('box')).height 爲 100pxcss

#box {
	background-color: skyblue;
	height: 100px;
	width: 100px;
	padding: 10px;
	border: 10px solid #999;
}
複製代碼

若是元素是 display: inline; 那麼獲得的結果是 auto 。
getBoundingClientRect 該方法可用於獲取元素相對於視口的 left 、top 、right 、bottom 以及元素寬高。 例如, document.getElementById('box').getBoundingClientRect().height 獲得的高度包括 內邊距和邊框寬度。
若是元素是 display: inline; 那麼獲得的高度是 0 。
獲取元素寬度的方法和結果跟上述同樣。java

相關文章
相關標籤/搜索