使用Element.getBoundingClientRect()来获取相对于viewport的位置,
2个元素top位置的差就是偏移量
Titlebody{
padding: 0;
margin: 0;
width: 100vw;
height: 100vh;
}
.container{
position: absolute;
left:10px;
top:10px;
width: 500px;
height: 500px;
background-color: #ffffff;
box-sizing: border-box;
border:1px solid #cccccc;
overflow: hidden;
}
.child{
width: 100%;
height: 200%;
background-color: red;
border: 1px solid red;
box-sizing: border-box;
}
.calcButton{
position: absolute;
left:0;
bottom:0;
width: 100px;
height: 50px;
box-sizing: border-box;
}
.child-wrapper{
position: absolute;
left:0;
right: 0;
top:0;
bottom:50px;
overflow-x: hidden;
overflow-y: auto;
}
计算
document.querySelector(".calcButton").addEventListener("click",function(){
var childWrapperRect=document.querySelector(".child-wrapper") .getBoundingClientRect();
var childRect=document.querySelector(".child") .getBoundingClientRect();
this.innerText="当前偏移-"+(childWrapperRect.top-childRect.top);
});