js 求定位元素距离页面的偏移量
2022-03-14 本文已影响0人
Peter_2B

<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>