基於js中style.width與offsetWidth的區別(詳解),

來源:互聯網
上載者:User

基於js中style.width與offsetWidth的區別(詳解),

作為一個初學者,經常會遇到在擷取某一元素的寬度(高度、top值...)時,到底是用 style.width還是offsetWidth的疑惑。

1. 當樣式寫在行內的時候,如 <div id="box" style="width:100px">時,用 style.width或者offsetWidth都可以擷取元素的寬度。

但是,當樣式寫在樣式表中時,如 #box{ width: 100px; }, 此時只能用offsetWidth來擷取元素的寬度,而style.width所返回的值為空白。

2. style.width 擷取的元素寬度只是div的寬度,不包括border、和padding所佔的寬度,且寬度值是帶單位px的。

offsetWidth 擷取的元素寬度為width+border+padding的值(不包括margin),且傳回值只為一個數值,不帶單位。

如下面的例子所示:

<head>    <script>      window.onload = function(){        var box = document.getElementById('box');        console.log(box.style.width);         console.log(box.offsetWidth);        }</script>  </head>  <body>    <div id="box" style="width:300px; height: 300px; padding:3px; margin: 1px; border: 1px solid red;"></div>  </body>

控制台輸出的第一個結果為:  300px

控制台輸出的第二個結果為:  308      註:300+ 3x2 +1x2 = 308, 且不帶單位

3. style.width 也可以在js中用來設定元素的寬度,而offsetWidth不可以。

如下面的例子所示:

<script>      window.onload = function(){        var box = document.getElementById('box');        box.style.width = '200px';        console.log(box.offsetWidth);        console.log(box.style.width);        box.offsetWidth = '400px';        console.log(box.offsetWidth);        console.log(box.style.width);      }    </script>  </head>  <body>    <div id="box" style="width:300px; height: 300px; padding:3px; margin: 2px; border: 1px solid red;"></div>  </body>

控制台輸出的結果分別為 208     200px     208      200px

也就是說通過style.width 設定寬度成功,而 通過offsetWidth設定寬度失敗。

以上這篇基於js中style.width與offsetWidth的區別(詳解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.