2013-10-04 189 views
3

單擊我想將滾動條定位到特定的div。我用這個代碼:滾動條位置

<a href="#sponsor">Go to Sponsor</a> 
... 
<div id="sponsor">Sponsor</div> 

的問題是,我的頭是固定的(隨高度50像素)和重疊的div#贊助商本身。

這裏http://jsfiddle.net/xqZ9y/

看看怎麼解決?

謝謝。

+3

可你工作擺弄一個例子請創建一個到目前爲止所做的小提琴(www.jsfiddle.net)? – BeNdErR

+1

在標題下的'div#sponsor'中添加一個50像素或更多的'padding-top'? – Brewal

+2

滾動條點擊是無關緊要的。你需要創建一個工作佈局。現在即使手動滾動,也應該會遇到同樣的問題。 – avrahamcool

回答

1

可以通過添加額外的元件繞過問題,用#sponsor

<span id="sponsor"></span> 
#sponsor { 
    width: 0; 
    height: 0; 
    position: relative: 
    top: 50px; 
} 
2

正確定位的問題是,一個標準的錨將帶你到目標通過設置的所述scrollTop的文檔是目標的偏移頂部。在你的情況下,這意味着該物品位於標題後面。解決這個問題的一種方法是覆蓋錨定點擊事件,以補償項目重新定位時的標題高度。

下面是一些jQuery的,將做到這一點...

$(function(){ 
    $("a[href^='#']").on("click.scrollFix", function(e) { 
     // cancel the click of the a href from taking you to the 
     // anchor by normal means 
     e.preventDefault();   

     // instead find the element and scroll to the elements position - the height of the  header 
     var targetSelector = $(this).attr("href"), 
      targetTop = $(targetSelector).offset().top, 
      headerHeight = $("#header").outerHeight(true); 

     $(document).scrollTop(targetTop - headerHeight); 
    }); 
}); 

,這裏是使用固定頭和一些垃圾內容:)

http://jsfiddle.net/QjheK/

+0

:) JavaScript解決方案將工作得很好。 +1 –