我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
我在一个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。
其他回答
我的解决方案结合了CMS的目标和前选择器。其他技术不考虑锚中的文本。调整高度和负边距到你需要的偏移量…
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}
正如@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;
}
如果您的锚是一个表元素或在一个表(行或单元格)中,上述方法就不能很好地工作。
我不得不使用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事件并非在所有浏览器中都可用。
我在每个h1元素之前添加了40px-height .vspace元素。
<div class="vspace" id="gherkin"></div>
<div class="page-header">
<h1>Gherkin</h1>
</div>
CSS中:
.vspace { height: 40px;}
它工作得很好,空间也没有堵塞。
我也在寻找这个问题的解决方案。对我来说,这很简单。
我有一个列表菜单与所有的链接:
<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>
下面是标题。
<h3>one</h3>
<p>text here</p>
<h3>two</h3>
<p>text here</p>
<h3>three</h3>
<p>text here</p>
<h3>four</h3>
<p>text here</p>
现在,因为我在页面顶部有一个固定的菜单,我不能让它去我的标签,因为它会在菜单后面。
相反,我在标签中放入了一个span标签,并带有正确的id。
<h3><span id="one"></span>one</h3>
现在使用2行CSS来正确定位它们。
h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}
更改顶部值以匹配固定标题的高度(或更多)。 现在我认为这也适用于其他元素。