javascript三大家族之offset demo代码
程序员文章站
2022-05-10 19:28:50
offsetwidth=width+padding+border+margin; offsetparent是指返回有定位的父级盒子,如果没有的话,返回的是body
offsett...
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> <p class="box" id="box"> <p class="box1" id="box1"> <p class="box2" id="box2"></p> </p> </p> <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>