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


当前回答

这对我来说很管用:

[id]::before {
  content: '';
  display: block;
  height:      75px;
  margin-top: -75px;
  visibility: hidden;
}

其他回答

@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>

这将从以前的答案中提取许多元素并组合成一个微小的(194字节缩小)匿名jQuery函数。调整fixedElementHeight为您的菜单或块元素的高度。

    (function($, window) {
        var adjustAnchor = function() {

            var $anchor = $(':target'),
                    fixedElementHeight = 100;

            if ($anchor.length > 0) {

                $('html, body')
                    .stop()
                    .animate({
                        scrollTop: $anchor.offset().top - fixedElementHeight
                    }, 200);

            }

        };

        $(window).on('hashchange load', function() {
            adjustAnchor();
        });

    })(jQuery, window);

如果你不喜欢这个动画,替换它

$('html, body')
     .stop()
     .animate({
         scrollTop: $anchor.offset().top - fixedElementHeight
     }, 200);

:

window.scrollTo(0, $anchor.offset().top - fixedElementHeight);

糟蹋版本:

 !function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);

你可以不用js也不用修改html。它´s css-only。

a[id]::before {
    content: '';
    display: block;
    height: 50px;
    margin: -30px 0 0;
}

这将在每个带id的a-tag之前附加一个伪元素。调整值以匹配头部的高度。

这是受到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();
});

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