我有一个固定的标题高度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;
}
发布于 2012-02-18 10:43:20
如果标题确实是固定的,那么将锚点放在一个可滚动的div中。然后包含锚点的div将滚动,而不是整个页面。访问小提琴并单击anchor1。它给了anchor2。以此类推。
http://jsfiddle.net/mrtsherman/CsJ3Y/3/
css -设置主体上隐藏的溢出,以防止默认滚动。在具有顶部和底部设置的新内容区域上使用绝对位置。这会强制其拉伸以适合其余的视口窗口。
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>
发布于 2012-10-30 14:42:26
如果使用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“类添加到您的锚点
发布于 2016-09-16 16:25:32
对于纯CSS解决方案,只需使用另一个带有相反页边距的div :)
<style>
.anchor {
margin-top: -50px;
margin-bottom: 50px;
}
</style>
<div id="n1" class="anchor"></div>
<div class="box"></div>
https://stackoverflow.com/questions/9338033
复制相似问题