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

当前回答

我认为这种方法更有用:

<h2 id=“bar” title=“Bar”>Bar</h2>

[id]:target {
    display: block;
    position: relative;
    top: -120px;
    visibility: hidden;
}

[id]:target::before {
    content: attr(title);
    top: 120px;
    position: relative;
    visibility: visible;
}

其他回答

官方引导采用答案:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; // Set the Appropriate Height
  height: 75px; // Set the Appropriate Height
  visibility: hidden; 
}

学分

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

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

a.anchor {
    display: block;
    position: relative;
    top: -60px;
    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,但另一个更受欢迎的问题因为这个问题而关闭了,我无法回答。

我使用@Jpsy的答案,但出于性能原因,我只在URL中存在散列时设置计时器。

$(function() {
      // Only set the timer if you have a hash
      if(window.location.hash) {
        setTimeout(delayedFragmentTargetOffset, 500);
      }
  });

function delayedFragmentTargetOffset(){
      var offset = $(':target').offset();
      if(offset){
          var scrollto = offset.top - 80; // minus fixed header height
          $('html, body').animate({scrollTop:scrollto}, 0);
          $(':target').highlight();
      }
  };
<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

这段代码应该可以达到目的。将标题栏的高度替换为45px。

编辑:如果使用jQuery是一个选项,我也成功地使用jQuery。带有偏移值设置的localScroll。偏移量选项是jQuery的一部分。scrollTo, jQuery。localScroll是在此基础上构建的。这里有一个演示:http://demos.flesler.com/jquery/scrollTo/(第二个窗口,在'offset'下)