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


当前回答

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

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

CSS中:

.vspace { height: 40px;}

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

其他回答

用可链接id来提供导航栏高度的隐藏span标签怎么样?

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

这里是小提琴:http://jsfiddle.net/N6f2f/7

我的解决方案结合了CMS的目标和前选择器。其他技术不考虑锚中的文本。调整高度和负边距到你需要的偏移量…

:target::before {
    content: '';
    display: block;
    height:      180px;
    margin-top: -180px;
}

对于现代浏览器,只需将CSS3:target选择器添加到页面。这将自动应用于所有的锚。

:target {
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}

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

这将从以前的答案中提取许多元素并组合成一个微小的(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);