我有一个固定的标题高度50px。在我的身体里,我有很多锚点。问题是,当我点击指向锚点的链接时,锚点出现在我的固定标题下,我丢失了50px的内容(我需要向上滚动50px来读取标题下的内容)。
有没有办法保留50px的锚点?我的身体充满了很多盒子(div),它们之间有一个边缘,所以我不能放置50px的空div然后锚定它。
HTML:
<div id="header"></div>
<div id="content">
<div class="box" id="n1"></div>
<div class="box" id="n2"></div>
<div class="box" id="n3"></div>
</div>
CSS:
#header{
height: 40px;
width: 100%;
margin: 0px;
padding: 0px;
position: fixed;
text-align: center;
z-index:2;
}
#content{
padding-top: 50px;
margin: 0px;
}
.box {
width: 80%;
margin-left: auto;
margin-right: auto;
vertical-align : top;
padding: 1.4%; /* Keep it in percent (%) */
margin-bottom: 30px;
min-height: 200px;
}
如果标题是真正固定的,那么将锚点放在可滚动的div中。然后包含锚点的div将滚动而不是整个页面。访问小提琴,然后单击anchor1。它转到了anchor2。等等。
http://jsfiddle.net/mrtsherman/CsJ3Y/3/
css - 设置隐藏在body上的溢出以防止默认滚动。在顶部和底部设置的新内容区域上使用绝对位置。这会强制它伸展以适应剩余的视口窗口。
body { overflow: hidden; }
#header { position: fixed; top: 0; left: 0; width: 100%; height: 50px; background: gray; border: 1px solid black; }
#content {
overflow: scroll;
position: absolute;
top: 50px;
bottom: 0px;
width: 100%;
border: 1px solid blue;
}
HTML
<div id="header">header</div>
<div id="content">
<div>
Page Content <br />
<a id="a1" href="#anchor2" name="anchor1">Anchor 1</a>
<a id="a2" href="#anchor1" name="anchor2">Anchor 2</a>
</div>
</div>
如果您使用jQuery,则使用此函数:
function scrollToAnchor() {
if($(".jquery-anchor").length > 0 && document.URL.indexOf("#") >= 0){
var anchor = document.URL.split("#")[1];
$(".jquery-anchor").each(function() {
if($(this).attr("name") == anchor) {
$("html,body").animate({
scrollTop: $(this).offset().top - 50},
'slow');
}
});
}
}
然后将类“jquery anchor”添加到您的锚点
对于纯CSS解决方案,只需使用另一个具有oposited margin的div :)
<style>
.anchor {
margin-top: -50px;
margin-bottom: 50px;
}
</style>
<div id="n1" class="anchor"></div>
<div class="box"></div>
我知道这是一个老线程 - 但也许其他人也有同样的问题。
机会正在为每个锚定的div设置一个顶部填充,如下所示:
.box {padding-top:50px; ...}
现在,您的锚点滚动将在没有任何空容器的情况下到达框,并且您在CSS中添加的填充将为您提供在标题下直接显示内容的空间。