获取元素到页面的距离

时间:2022-12-20 20:59:08

<style type="text/css">
* {
margin: 0;
padding: 0;
}

.father {
width: 500px;
height: 500px;
background: pink;
margin: 100px auto;
padding-top: 1px;
position: relative;
}

.son {
width: 200px;
height: 200px;
background: deepskyblue;
margin: 20px auto;
position: absolute;
}

.f1,.f2{
position: relative;
margin: 100px auto;
}
</style>


<body>
<div class="f1">
<div class="f2">
<div class="f3">
<div class="father">
<div class="son"></div>
</div>


</div>
</div>
</div>

</body>


<script type="text/javascript">


//1.获取元素
var son = document.getElementsByClassName('son')[0];


//2.自定义函数获取元素到页面的距离
function offset(element) {

//3.1获取当前元素的offsetTop
var pos = {left:0,top:0};


//3.2获取元素有定位的父级的位置
var parents = element.offsetParent;

//3.3先加上自己的left  top
pos.left += element.offsetLeft;

pos.top += element.offsetTop;

while(parents && !/html|body/i.test(parents.tagName)) {

pos.top += parents.offsetTop;
pos.left += parents.offsetLeft;

parents = parents.offsetParent;

}

return pos

}


//4.执行函数 并且传递一个元素,帮我们计算元素到页面的位置
var obj = offset(son);

console.log(obj.top);
</script>