我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
受Alexander Savin启发的纯css解决方案:
a[name] {
padding-top: 40px;
margin-top: -40px;
display: inline-block; /* required for webkit browsers */
}
如果目标仍然不在屏幕上,你可以选择添加以下内容:
vertical-align: top;
其他回答
用可链接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
再加上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;
}
不要使用固定位置的导航条,它覆盖了页面的其余内容(整个页面主体都是可滚动的),而是考虑使用静态导航条的不可滚动主体,然后将页面内容放在绝对位置的可滚动div中。
也就是说,有这样的HTML…
<div class="static-navbar">NAVBAR</div>
<div class="scrollable-content">
<p>Bla bla bla</p>
<p>Yadda yadda yadda</p>
<p>Mary had a little lamb</p>
<h2 id="stuff-i-want-to-link-to">Stuff</h2>
<p>More nonsense</p>
</div>
... 和CSS是这样的:
.static-navbar {
height: 100px;
}
.scrollable-content {
position: absolute;
top: 100px;
bottom: 0;
overflow-y: scroll;
width: 100%;
}
然而,这种方法有一个显著的缺点,那就是当页面标题中的元素被聚焦时,用户将无法使用键盘滚动页面(例如,通过向上和向下箭头或page up和page down键)。
下面是一个演示这个操作的JSFiddle。
对于现代浏览器,只需将CSS3:target选择器添加到页面。这将自动应用于所有的锚。
:target {
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
如果您的锚是一个表元素或在一个表(行或单元格)中,上述方法就不能很好地工作。
我不得不使用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事件并非在所有浏览器中都可用。