2013-10-04 188 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 –