盒子的偏移量
盒子相对于offsetParent偏移量:offsetLeft,offsetTop.
offsetParent:盒子向上找的第一个有定位的元素,没有就是body,body的offsetParent是null
现在,想求任意盒子相对body的偏移量.<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { padding: 0; margin: 0; font-size: 14px; } #outer { width: 300px; height: 300px; padding: 50px; margin: 30px; border: 10px solid #000; background-color: pink; } #inner { width: 200px; height: 200px; padding: 40px; margin: 30px; border: 10px solid #000; background-color: #69f; } #center { width: 100px; height: 100px; padding: 30px; margin: 30px; border: 10px solid #000; background-color: #6f9; } </style> </head> <body> <div id="outer"> <div id="inner"> <div id="center"></div> </div> </div> <script> var outer = document.getElementById("outer"); var inner = document.getElementById("inner"); var center = document.getElementById("center"); console.log(center.offsetParent); // body console.log(center.offsetLeft); // 200,这里是center这个盒子(包括border)的左上角离inner盒子内容区(不包括border)的左上角的距离 console.log(center.offsetTop); // 200 inner.style.position = outer.style.position = "relative"; console.log(center.offsetParent); // inner console.log(center.offsetLeft); // 70,这里是center这个盒子(包括border)的左上角离inner盒子内容区(不包括border)的左上角的距离 console.log(center.offsetTop); // 70 console.log(inner.offsetParent); // outer console.log(inner.offsetLeft); // 80 console.log(inner.offsetTop); // 80 console.log(outer.offsetParent); // body console.log(outer.offsetLeft); // 30 console.log(outer.offsetTop); // 30
// center相对body的偏移量
console.log(center.offsetLeft + (center.offsetParent.clientLeft + center.offsetParent.offsetLeft) + (center.offsetParent.offsetParent.clientLeft + center.offsetParent.offsetParent.offsetLeft)); // 200 function offset(ele) { var parent = ele.offsetParent, left = ele.offsetLeft, top = ele.offsetTop;
// 只要不是null while (parent) { // ie8的offset已经加上了父元素的clientLeft if (navigator.userAgent.indexOf("MSIE 8.0") === -1) { // 父级参照物的边框 left += parent.clientLeft; top += parent.clientTop; } left += parent.offsetLeft; top += parent.offsetTop; parent = parent.offsetParent; } return { left, top }; } console.log(offset(center)) </script> </body> </html>