![](https://img.haomeiwen.com/i20409039/6b24e9434c1a7415.png)
定位元素黄色box在绿色box和灰色box中,距离页面body偏移量
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.grandfather{
width: 300px;
height: 300px;
border: 10px solid #ccc;
left: 50px;
position: absolute;
}
.father{
width: 200px;
height: 200px;
border: 10px solid green;
margin-left: 50px;
position: relative;
}
.son{
width: 100px;
height: 100px;
border: 10px solid orange;
margin-left: 50px;
}
</style>
<script type="text/javascript">
var son = document.querySelector('.son');
console.log(son.offsetLeft);
console.log( getElementLeft(son) );
function getElementLeft(eleObj){
// 当前元素距有定位的父元素的左偏移量
var currentLeft = eleObj.offsetLeft;
// 找到当前元素有定位的父元素
var parent = eleObj.offsetParent;
// 最外层是/没有定位父级就是基于<body/>, body.offsetParent是null.
while(parent != null){
// 当前元素做偏移量 + 父元素的左边border宽度 + 父元素的左偏移量
currentLeft = currentLeft + parent.clientLeft + parent.offsetLeft;
console.log(parent);
parent = parent.offsetParent;
}
return currentLeft;
}
</script>
网友评论