如果我在HTML页面中有一个非滚动头,固定在顶部,有一个定义的高度:

是否有一种方法可以使用URL锚(#fragment部分)让浏览器滚动到页面中的某一点,但仍然尊重固定元素的高度,而不需要JavaScript的帮助?

http://example.com/#bar
WRONG (but the common behavior):         CORRECT:
+---------------------------------+      +---------------------------------+
| BAR///////////////////// header |      | //////////////////////// header |
+---------------------------------+      +---------------------------------+
| Here is the rest of the Text    |      | BAR                             |
| ...                             |      |                                 |
| ...                             |      | Here is the rest of the Text    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

当前回答

使用这个脚本

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top -140
    }, 1000);
});

其他回答

我在这里和其他地方的许多答案都遇到了很多麻烦,因为我的书签锚是FAQ页面中的部分标题,所以抵消标题并没有帮助,因为其余的内容只是停留在原地。所以我想我应该发帖。

我最终做的是几个解决方案的组合:

CSS: .bookmark { margin-top: -120 px; padding-bottom: 120 px; 显示:块; }

其中“120px”是你的固定标题高度(可能加上一些边距)。

书签链接HTML: <a href="#01">你的常见问题是什么来着?< / > 书签内容HTML: <span class="bookmark" id="01"></span> 你的常见问题是什么来着?< / h3 > <p>一些常见问题的文本,后面跟着 < p >…</p>

这个解决方案的优点是span元素不仅隐藏,而且本质上是折叠的,不会填充您的内容。

我不能对这个解决方案有太多的功劳,因为它来自不同的资源,但它最适合我的情况。

你可以在这里看到实际的结果。

你可以试试这个:

<style>
h1:target { padding-top: 50px; }
</style>

<a href="#bar">Go to bar</a>

<h1 id="bar">Bar</h1>

将顶部填充值设置为头部的实际高度。这将在你的标题顶部引入一个轻微的额外间隙,但它只会在用户跳转到锚点然后向上滚动时才可见。我现在已经为我的网站制定了这个解决方案,但它只在页面顶部显示一个固定的小栏,没有太高。

上面的答案创建了一个60px高的标签,屏蔽了其他因此停止工作的链接。我发现这个方法没有副作用。

<a class="anchor" id="top"></a>

a.anchor {
    display: block;
    position: relative;
    top: -60px;
    visibility: hidden;
}

我发现我必须同时使用muttenxd和Badabam的CSS解决方案,因为第一个在Chrome中不起作用,第二个在Firefox中不起作用:

a.anchor { 
  padding-top: 90px;
}

a.anchor:before { 
  display: block;
  content: "";
  height: 90px;
  margin-top: -90px;
}

<a class="anchor" name="shipping"></a><h2>Shipping (United States)</h2>
...

我使用这种方法:

/* add class="jumptarget" to all targets. */

.jumptarget::before {
  content:"";
  display:block;
  height:50px; /* fixed header height*/
  margin:-50px 0 0; /* negative fixed header height */
}

它在每个目标之前添加一个隐形元素。支持IE8+。

这里有更多的解决方案: http://nicolasgallagher.com/jump-links-and-viewport-positioning/