標籤:des style blog io color ar os sp strong
js元素的offsetWidth與clientWidth很相似,因此放在一起記錄。
1、clientWidth與offsetWidth
clientWidth=元素內容地區寬度+水平內邊距padding.
offsetWidth=元素的內容地區寬度+水平內邊距padding+邊框的寬度。
因此,可以認為:
offsetWidth=clientWidth+邊框寬度。
通過執行個體驗證下:
<div style="width:500px;height:300px;background-color:#00f;position:relative;" id="div3">
sdsdsd
<div id="div2" style="width:300px;height:300px;border:10px solid #ccc;background-color:limegreen;padding:10px;">sdsd </div>
</div>var div2 = document.getElementById("div2");
var clientWidth = div2.clientWidth;
var clientHeight = div2.clientHeight;
console.log("clientHeight:"+clientHeight+" clientWidth:"+clientWidth);
var offsetWidth = div2.offsetWidth;
var offsetHeight = div2.offsetHeight;
console.log("offsetHeight:"+offsetHeight+" offsetWidth:"+offsetWidth);
FF下的console:
因,div2的寬度時300px, 且padding為10px,根據以上描述,則clientWidth等於內容地區寬度300+內邊距10*2(一個是paddingLeft,一個是paddingRight)=320px;
其他計算類似。
2、offsetParent
元素的offsetParent並不是元素的父元素,判斷元素的offsetParent要根據以下情況:
1)當DOM結構層次中的元素均沒有進行css定位(設定position為absolute或relative),則offsetParent為根目錄;
2)當元素的父元素沒有進行css定位,則offsetParent取最近的已經定位的元素;
3)當元素的父元素進行了css定位,則offsetParent為父元素;
js的offsetWidth,clientWidth及offsetParent