我知道.scrollTo(0,0)为window工作,并将您返回到页面顶部。但我的目标是回到页面上某些元素的顶部。我怎么能这么做?
function returnToTopElement(clickingObjId, element){
let clickOn = document.getElementById(clickingObjId);
let topElement = document.getElementById(element);
clickOn.addEventListener('click', function(){
topElement.scrollTo(0,0);
});
};
returnToTopElement("top-button", "elem-b"); .menu{
position: fixed;
background-color: red;
width: 100%;
height: 30px;
top: 0;
}
.elem-a{
height: 200px;
width: 200px;
background-color: #f6f6f6;
color: black;
}
.elem-b{
height: 300px;
width: 200px;
background-color: #263B42;
color: white;
}
.top-button{
margin-top: 200px;
cursor: pointer;
}
.top-button:hover{
background-color: #b2b2b2;
} <div class="menu"> Menu </div>
<div>
<div class="elem-a"> a </div>
<div class="elem-b" id="elem-b">
b
<p class="top-button" id="top-button"> Return to the top </p>
</div>
</div>
发布于 2020-04-03 12:06:58
HTMLElement.offsetTop是该元素的顶部边框到其偏移父母的顶部边框之间的距离,而不是到文档顶部的距离。计算两个元素之间的相对距离也很复杂。在您的情况下,您可以使用以下方法计算它:
topElement.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top但如果有的话,这并不代表最高利润。因此,如果想要包含这样的最高边距,那么您可能需要更进一步的。
topElement.getBoundingClientRect().top
- topElement.getComputedStyle().getPropertyValue('margin-top')
- document.documentElement.getBoundingClientRect().top您可能想知道是否有一个不那么麻烦的方法,但实际上,这是您必须做的,在大多数情况下。
https://stackoverflow.com/questions/61010777
复制相似问题