如何使用散列标签(“一个名字”)去页面上的位置,但在顶部说明一个固定的元素

How use hash tag ("a name") to go to spot on page but account for a fixed element at top?

本文关键字:一个 位置 元素 说明 顶部 标签 何使用 一个名字      更新时间:2023-09-26

在网站上,顶部有一个菜单栏,它是position: fixedheight: 4em;。当我单击一个散列链接<a href="#someName">go to</a>时,它会移动页面,将<a name="someName"></a>放置在窗口的顶部,这意味着它位于顶部栏的下方,并被部分隐藏。我该如何解释?

http://jsfiddle.net/x3gr8s8z/

HTML:

<div class="topbar"></div>
<br /><br /><br /><br /><br />
<a href="#link">click me</a>
<a name="link"></a>
Going to here

CSS:

.topbar
{
    position: fixed;
    width: 100%;
    height: 4em;
    background-color: #cccccc;
}

您可以捕获hashchange事件并将窗口向下滚动固定元素的高度。

window.addEventListener('hashchange', function() {
    window.scrollBy(0, -40);
});

你可以使用而不是40

document.querySelector('.topbar').getClientBoundingRect().height