2012-02-18 51 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> 
相關問題