js的offsetWidth,clientWidth及offsetParent

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.