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


当前回答

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

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

其他回答

我找到了这个解决方案:

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

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

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

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

我在一个TYPO3网站上遇到了这个问题,其中所有的“内容元素”都用类似这样的东西包装:

<div id="c1234" class="contentElement">...</div>

我改变了渲染,所以它是这样渲染的:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

这个CSS:

.anchor{
    position: relative;
    top: -50px;
}

固定的topbar是40px高,现在锚再次工作,并在topbar下10px开始。

这种技术的唯一缺点是你不能再使用:target。

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

你也可以用follow attr添加一个锚:

(text-indent:-99999px;)
visibility: hidden;
position:absolute;
top:-80px;    

并给父容器一个相对的位置。

很适合我。