目录
2、padding + width | padding + height
3、border + padding + width | border + padding + height
1、width | height - 获取盒子的内容高宽
parseInt(getComputedStyle(ele, null).getPropertyValue('width'))
parseInt(getComputedStyle(ele, null).getPropertyValue('height'))
---- 例如左图,200*200的区域的高宽
2、padding + width | padding + height
注意:此为子级的可活动范围
clientWidth
clientHeight
- --- 例如左图,(200+(30*2))*(200+(30*2))的区域的高宽
3、border + padding + width | border + padding + height
offsetWidth
offsetHeight
- --- 例如左图,的区域的高宽 270*270
4、结合绝对定位,距离最近定位父级的Top | Left
offsetTop
offsetLeft
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>js盒模型</title> <style type="text/css"> .sup { width: 200px; height: 200px; padding: 30px; border: 5px solid black; background-color: orange; margin: 20px; position: relative; } .sub { width: 100px; height: 100px; padding: 20px; border: 5px solid black; background-color: red; position: absolute; top: 0; left: 20px; } </style> </head> <body> <div class="sup"> <div class="sub"></div> </div> </body> <script type="text/javascript"> var sup = document.querySelector('.sup'); // 盒子content的width var width = parseInt(getComputedStyle(sup, null).width); console.log(width); // 盒子padding+width => 子级的可活动范围 var p_width = sup.clientWidth; console.log(p_width); // 盒子border+padding+width => 可视区域 var b_p_width = sup.offsetWidth; console.log(b_p_width); // 盒子距离定位父级的top,left var sup_top = sup.offsetTop; var sup_left = sup.offsetLeft; console.log(sup_top); console.log(sup_left); var sub = document.querySelector('.sub'); // 父级定位(relative)后,子级活动区域为父级的client(padding+width)区域 var sub_top = sub.offsetTop; var sub_left = sub.offsetLeft; console.log(sub_top); console.log(sub_left); </script> </html>
JavaScript - JS盒模型
最新推荐文章于 2023-09-18 19:09:03 发布