一.用原生js如何获取文档中任意一个元素与文档顶部的距离
//方式一
const offset=ele =>{
let result={
left:0,top:0
}
const getOffset=(node,init)=>{
//如何不是一个元素节点
if(node.nodeType!=1){
return
}
//获取定位类型
let position=window.getComputedStyle(node)['position']
//如果定位类型等于static
if(typeof(init)==="undefined"&&position==="static"){
//递归父节点
getOffset(node.parentNode)
return
}
//累计计算该元素到父元素之间的距离
result.top=node.offsetTop+result.top-node.scrollTop
result.left=node.offsetLeft+result.left-node.scrollLeft
if(position==='fixed'){
return
}
getOffset(node.parentNode)
if(window.getComputedStyle(ele)['display']==='none'){
return result
}
console.info('111111',result)
}
getOffset(ele,true)
console.info(result)
return result
}
//方式2
const offset1=ele=>{
let result={
left:0,top:0
}
if(!ele.getClientRects().length){
return result
}
if(window.getComputedStyle(ele)["display"]==='none'){
return result
}
result=ele.getBoundingClientRect()
var docElement=ele.ownerDocument?.documentElement
console.info("top",result.top+window.pageYOffset-docElement.clientTop,'left',result.left+window.pageXOffset-docElement.clientLeft)
return{
top:result.top+window.pageYOffset-docElement.clientTop,
left:result.left+window.pageXOffset-docElement.clientLeft
}
}
二.html调用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./"></script>
</head>
<style>
#box1{
background-color: aqua;
width:500px;
height:1200px;
position:relative;
left:10px;
top:10px;
}
#box2{
background-color: pink;
width:400px;
position:absolute;
top:50px;
left:50px;
height:50px;
}
</style>
<body>
<div id="box1">
<div id="box2"></div>
</div>
<script>
window.addEventListener("load",function(){
let element=document.getElementById('box2')
console.info(element)
offset1(element)
// offset(element)
})
</script>
</body>
</html>