我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。


当前回答

这是受到Shouvik回答的启发-与他的概念相同,只是固定头的大小没有硬编码。只要你的固定头在第一个头节点中,这应该“正常工作”。

/*jslint browser: true, plusplus: true, regexp: true */

function anchorScroll(fragment) {
    "use strict";
    var amount, ttarget;
    amount = $('header').height();
    ttarget = $('#' + fragment);
    $('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
    return false;
}

function outsideToHash() {
    "use strict";
    var fragment;
    if (window.location.hash) {
        fragment = window.location.hash.substring(1);
        anchorScroll(fragment);
    }
}

function insideToHash(nnode) {
    "use strict";
    var fragment;
    fragment = $(nnode).attr('href').substring(1);
    anchorScroll(fragment);
}

$(document).ready(function () {
    "use strict";
    $("a[href^='#']").bind('click',  function () {insideToHash(this); });
    outsideToHash();
});

其他回答

我在每个h1元素之前添加了40px-height .vspace元素。

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

CSS中:

.vspace { height: 40px;}

它工作得很好,空间也没有堵塞。

我找到了这个解决方案:

<a name="myanchor">
    <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>

这不会在内容和锚链接中产生任何差距,效果非常好。

对于同样的问题,我使用了一个简单的解决方案:在每个锚上放置40px的填充顶部。

再加上Ziav的回答(感谢Alexander Savin),我需要使用老式的<a name="…">…</a> as we're using <div id="…">…</div>用于代码中的另一个目的。我在使用display: inline-block时遇到了一些显示问题——每个<p>元素的第一行都略微右缩进(在Webkit和Firefox浏览器上都是如此)。我最终尝试了其他的显示值和display: table-标题对我来说非常适合。

.anchor {
  padding-top: 60px;
  margin-top: -60px;
  display: table-caption;
}

@AlexanderSavin的解决方案在WebKit浏览器中对我来说很棒。

另外,我不得不使用:target伪类,它将样式应用到选定的锚来调整FF, Opera和IE9中的填充:

a:target {
  padding-top: 40px
}

注意,这种风格不适合Chrome / Safari,所以你可能不得不使用css-hacks,条件注释等。

我还想注意到,Alexander的解决方案工作,因为目标元素是内联的。如果你不想要链接,你可以简单地改变显示属性:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>