本文參考千古壹號(hào)的git項(xiàng)目,并自己實(shí)踐驗(yàn)證
方式一:通過(guò)DOM節(jié)點(diǎn)的style樣式獲取
element.style.width/height
缺點(diǎn):這種方式,只能獲取行內(nèi)樣式,不能獲取內(nèi)嵌的樣式和外鏈的樣式

image.png
html:
<div class="container">
包裹
<div class="standard-box" id="standardbox" style="width:200px;
height:200px;
padding:20px;
border:10px solid green;
margin: 20px;
box-sizing:content-box;">
標(biāo)準(zhǔn)盒子
</div>
</div>
JS:
window.onload=function(){
let elementID = document.getElementById('standardbox');
elementID.onclick = function(){
let elementWidth = elementID.style.width;
alert('寬度'+elementWidth + '\n高度'+ elementID.style.height);
}
}
方式二(通用型)
window.getComputedStyle( ).width/height
行內(nèi)樣式、內(nèi)嵌樣式,外鏈樣式都可以讀取到,谷歌、火狐、IE皆可用

image.png
html
<link rel="stylesheet" type="text/css" href="test.css"/>
<!--test.css的內(nèi)容:
.standard-box{
width:200px;
height:200px;
padding:20px;
border:10px solid green;
margin: 20px;
box-sizing:content-box;
}-->
<div class="container">
包裹
<div class="standard-box" id="standardbox">
標(biāo)準(zhǔn)盒子
</div>
</div>
js
window.onload=function(){
let elementID = document.getElementById('standardbox');
elementID.onclick = function(){
alert('寬度'+window.getComputedStyle(elementID).width + '\n高度'+ window.getComputedStyle(elementID).height);
}
}
方式三(IE獨(dú)有,Edge也用不了)
element.currentStyle.width

image.png
JS
window.onload=function(){
let elementID = document.getElementById('standardbox');
elementID.onclick = function(){
alert('寬度'+elementID.currentStyle.width + '\n高度'+ elementID.currentStyle.height);
}
}
方式四(相對(duì)于視窗的位置)
element.getBoundingClientRect().width/height
兼容谷歌、火狐、IE、Edge
getBoundingClientRect().width獲取到的其實(shí)是父級(jí)的右邊距離瀏覽器原點(diǎn)(0,0)左邊距離瀏覽器原點(diǎn)(0,0)的距離,即父級(jí)的寬度+2padding+2border
該函數(shù)返回一個(gè)Object對(duì)象,該對(duì)象有6個(gè)屬性:top,lef,right,bottom,width,height;
如下圖,盒模型的寬度=content:200px+padding:20px 2 + border:10px
2 =260px

image.png

image.png
css:
.standard-box{
width:200px;
height:200px;
padding:20px;
border:10px solid green;
margin: 20px;
box-sizing:content-box;
}
html:
<div class="container">
包裹
<div class="standard-box" id="standardbox">
標(biāo)準(zhǔn)盒子
</div>
</div>
JS:
window.onload=function(){
let elementID = document.getElementById('standardbox');
elementID.onclick = function(){
alert('寬度'+elementID.getBoundingClientRect().width + '\n高度'+ elementID.getBoundingClientRect().height);
}
}