1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>js盒模型</title> 6 7 <style type="text/css"> 8 .sup { 9 width: 200px; 10 height: 200px; 11 padding: 30px; 12 border: 5px solid black; 13 background-color: orange; 14 margin: 20px; 15 position: relative; 16 } 17 18 .sub { 19 width: 100px; 20 height: 100px; 21 padding: 20px; 22 border: 5px solid black; 23 background-color: red; 24 position: absolute; 25 top: 0; 26 left: 20px; 27 } 28 </style> 29 </head> 30 <body> 31 <div class="sup"> 32 <div class="sub"></div> 33 </div> 34 </body> 35 <script type="text/javascript"> 36 var sup = document.querySelector('.sup'); 37 // 盒子content的width 38 var width = parseInt(getComputedStyle(sup, null).width); 39 console.log(width); 40 41 // 盒子padding+width => 子级的可活动范围 42 var p_width = sup.clientWidth; 43 console.log(p_width); 44 45 // 盒子border+padding+width => 可视区域 46 var b_p_width = sup.offsetWidth; 47 console.log(b_p_width); 48 49 // 盒子距离定位父级的top,left 50 var sup_top = sup.offsetTop; 51 var sup_left = sup.offsetLeft; 52 console.log(sup_top); 53 console.log(sup_left); 54 55 56 var sub = document.querySelector('.sub'); 57 // 父级定位(relative)后,子级活动区域为父级的client(padding+width)区域 58 var sub_top = sub.offsetTop; 59 var sub_left = sub.offsetLeft; 60 console.log(sub_top); 61 console.log(sub_left); 62 63 </script> 64 </html>