首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何移动到元素的顶部?

如何移动到元素的顶部?
EN

Stack Overflow用户
提问于 2020-04-03 11:23:18
回答 1查看 59关注 0票数 2

我知道.scrollTo(0,0)window工作,并将您返回到页面顶部。但我的目标是回到页面上某些元素的顶部。我怎么能这么做?

代码语言:javascript
运行
复制
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");
代码语言:javascript
运行
复制
    .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;
    }
代码语言:javascript
运行
复制
    <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>

EN

Stack Overflow用户

回答已采纳

发布于 2020-04-03 12:06:58

HTMLElement.offsetTop是该元素的顶部边框到其偏移父母的顶部边框之间的距离,而不是到文档顶部的距离。计算两个元素之间的相对距离也很复杂。在您的情况下,您可以使用以下方法计算它:

代码语言:javascript
运行
复制
topElement.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top

但如果有的话,这并不代表最高利润。因此,如果想要包含这样的最高边距,那么您可能需要更进一步的

代码语言:javascript
运行
复制
topElement.getBoundingClientRect().top 
- topElement.getComputedStyle().getPropertyValue('margin-top')
- document.documentElement.getBoundingClientRect().top

您可能想知道是否有一个不那么麻烦的方法,但实际上,这是您必须做的,在大多数情况下。

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61010777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档