我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
改变位置属性的解决方案并不总是可能的(它会破坏布局),因此我建议这样做:
HTML:
<a id="top">Anchor</a>
CSS:
#top {
margin-top: -250px;
padding-top: 250px;
}
用这个:
<a id="top"> </a>
为了减少重叠,设置font-size为1px。空锚将无法在某些浏览器中工作。
其他回答
对于同样的问题,我使用了一个简单的解决方案:在每个锚上放置40px的填充顶部。
我找到了这个解决方案:
<a name="myanchor">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>
这不会在内容和锚链接中产生任何差距,效果非常好。
我在一个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。
你可以不用js也不用修改html。它´s css-only。
a[id]::before {
content: '';
display: block;
height: 50px;
margin: -30px 0 0;
}
这将在每个带id的a-tag之前附加一个伪元素。调整值以匹配头部的高度。
我也曾面临过类似的问题,不幸的是,在实施了上述所有解决方案后,我得出了以下结论。
我的内部元素有一个脆弱的CSS结构和实现位置相对/绝对发挥,完全打破了页面设计。 CSS不是我的强项。
我写了这个简单的滚动js,它解释了由于标题引起的偏移,并将div重新定位到下面大约125像素。请用你认为合适的。
HTML
<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
JavaScript
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offset height of header here too.
}, 1000);
return false;
}
}
});
点击这里查看实时实现。