2012-02-18 52 views
17

我有一个固定的标题高度50px。在我的身体里,我有很多锚点。问题是,当我点击指向锚点的链接时,锚点出现在我的固定标题下,并且丢失了50px的内容(我需要向上滚动50px才能阅读标题下的内容)。有没有办法在CSS中保留一个锚?

有没有办法让边距达到50px?我的身体充满了很多箱(申报单)与自理之间的余量,所以我不能到位50像素的空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; 
} 
+0

这可能有助于锚链接与固定标题: http://www.pixelflips.com/blog/anchor-links-with-a-fixed-header/ – toto 2013-01-15 16:16:43

回答

5

如果标题是真正固定的,那么把你的锚在滚动的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>​ 
+0

我更新了我的初始帖子。看看我的代码..我试着用overflow-y:scroll但是,它仍然不能工作。 – 2012-02-18 02:54:36

+0

所有浏览器都不支持Overflow-y。 – 2012-02-18 02:59:50

+0

@mrtsherman我当我点击anchor1时,我需要查看“Anchor1”及其内容。相同的anchor2 .. – 2012-02-18 03:01:39

5

如果你使用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” 添加到你的锚

+0

我错过了一些东西。什么叫'scrollToAnchor()'? – zipzit 2014-03-21 20:01:59

+0

我把它放在一个函数中,使它在ajax中工作。它通过$(document).ready()在文档加载时调用,而且在通过回调函数每次ajax往返之后调用。 – ndemoreau 2014-03-22 22:29:37

+0

我终于明白了。实际上,我添加了: //拦截所有锚点击 jQuery(“body”)。on(“click”,“a”,scrollToAnchor); – zipzit 2014-03-23 04:37:14

2

对于纯CSS解决方案只需使用另一个带有oposited margin的div :)

<style> 
.anchor { 
    margin-top: -50px; 
    margin-bottom: 50px; 
} 
</style> 

<div id="n1" class="anchor"></div> 
<div class="box"></div> 
相关问题