offsetWidth=Width+padding+border+margin; offsetParent是指返回有定位的父级盒子,如果没有的话,返回的是body
offsetTop是指距离定位盒子顶部的距离;offsetLeft是指距离定位盒子左边的距离。以上得到的都是数值类型的数据,demo代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> * { margin: 0; padding: 0; } .box { width: 600px; height: 600px; margin: 20px; padding: 20px; border: 1px solid #000; position: absolute; } .box1 { width: 400px; height: 400px; margin: 20px; padding: 20px; border: 1px solid #000; } .box2 { width: 100px; height: 100px; margin: 20px; padding: 20px; border: 1px solid #000; } </style> </head> <body> <div class="box" id="box"> <div class="box1" id="box1"> <div class="box2" id="box2"></div> </div> </div> <script type="text/javascript"> var box2 = document.getElementById("box2"); var box = document.getElementById("box"); var box1 = document.getElementById("box1"); console.log(box2.offsetWidth); //offsetWidth=width+padding+border+margin console.log(box.offsetTop); //offsetTop console.log(box1.offsetTop); //offsetTop是相对于有定位盒子的距离 console.log(box.offsetLeft); console.log(box1.offsetLeft);//offsetLeft是相对于有定位盒子的距离 console.log(typeof(box1.offsetLeft)) </script> </body> </html>