如果我在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    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

当前回答

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

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

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

其他回答

一个非常简单的CSS答案是把它放在你的样式表的顶部:

a{padding-top: 90px;}
a:link{padding-top: unset;}

第一种样式管理所有锚标记,第二种样式使用超链接锚标记。

注意:这目前适用于Firefox和Edge,但不适用于Chrome。

如果你不能或不想设置一个新类,在CSS的:target伪类中添加一个固定高度的::

:target::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}

或者使用jQuery相对于:target滚动页面:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

我对上面列出的答案没有任何运气,最终使用了这个完美的解决方案……

在想要设置锚点的地方创建一个空白span。

<span class="anchor" id="section1"></span>
<div class="section"></div>

并应用以下类:

.anchor {
  display: block;
  height: 115px;       /* same height as header */
  margin-top: -115px;  /* same height as header */
  visibility: hidden;
}

这个解决方案将工作,即使部分有不同的颜色背景!我在这个环节找到了解决方案。

使用jQuery的最小侵入性方法:

链接:

<a href="#my-anchor-1" class="anchor-link">Go To Anchor 1</a>

内容:

<h3 id="my-anchor-1">Here is Anchor 1</a>

脚本:

$(".anchor-link").click(function() {
    var headerHeight = 120;
    $('html, body').stop(true, true).animate({
        scrollTop: $(this.hash).offset().top - headerHeight
    }, 750);
    return false;
});

通过将锚链接类分配给链接,其他链接(如手风琴或制表符控件)的行为不会受到影响。

这个问题不需要javascript,但另一个更受欢迎的问题因为这个问题而关闭了,我无法回答。

你可以用jQuery做到这一点:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);