我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
@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>
其他回答
我遇到了同样的问题,最终手动处理点击事件,如下所示:
$('#mynav a').click(() ->
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 40
}, 200
return false
)
当然,滚动动画是可选的。
正如@moeffju所建议的,这可以通过CSS实现。我遇到的问题(我很惊讶我没有看到讨论)是用填充或透明边框重叠之前的元素的技巧,可以防止在这些部分的底部进行悬停和单击操作,因为下面的部分在z轴次序中更高。
我发现的最好的解决办法是把部分内容放在一个div,是在z-index: 1:
// Apply to elements that serve as anchors
.offset-anchor {
border-top: 75px solid transparent;
margin: -75px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
position: relative;
z-index: 1;
}
你可以不用js也不用修改html。它´s css-only。
a[id]::before {
content: '';
display: block;
height: 50px;
margin: -30px 0 0;
}
这将在每个带id的a-tag之前附加一个伪元素。调整值以匹配头部的高度。
再加上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;
}
如果您的锚是一个表元素或在一个表(行或单元格)中,上述方法就不能很好地工作。
我不得不使用javascript和绑定到窗口hashchange事件来解决这个问题(演示):
function moveUnderNav() {
var $el, h = window.location.hash;
if (h) {
$el = $(h);
if ($el.length && $el.closest('table').length) {
$('body').scrollTop( $el.closest('table, tr').position().top - 26 );
}
}
}
$(window)
.load(function () {
moveUnderNav();
})
.on('hashchange', function () {
moveUnderNav();
});
*注意:hashchange事件并非在所有浏览器中都可用。