2012-09-05 48 views
1

我已经添加顶部菜单作为与位置的div:固定。 它被放置在页面的顶部,因此它覆盖了部分内容。 我将布局向下移动,所以一般情况下都可以,但如果用户单击任何锚点链接,页面会滚动到锚点位于顶部的位置。但它被顶部菜单覆盖。 有没有办法来捕获锚事件和处理它与JavaScript(和jQuery,如果有必要)?如何在锚定导航后向下滚动页面?

+0

向我们展示您到目前为止尝试过的方法。 – Lowkase

+0

是的,代码请 –

+0

改写你的问题,强调这部分 - *'捕获锚事件和处理它* –

回答

2

您可以使用这样的事情:

$('a').click(function(){ 
    $('html').scrollTop($($(this).attr('href')).position().top + menu_height_offset) 
}) 

要获得锚位置

$($(this).attr('href')).position().top 

为了使偏移有关的固定菜单

menu_height_offset 

为了使移动滚动

$('html').scrollTop() 

http://api.jquery.com/scrollTop/

http://api.jquery.com/position/

+0

似乎这就是我想要的。尝试... – ABTOMAT

+0

好吧,如果锚是用'name'属性制作的,但这不起作用,但我解决了。通常这有助于,谢谢! – ABTOMAT

1

你需要计算元素和sroll的偏移,offset of element - height of the navigationbar - 位置:

$("a").on("click",function(){ 
    // height of the navigation bar 
    var height= $("#nav").outerHeight(); 
    // position of the referenced dom-element 
    var pos = $($(this).attr("href")).position().top; 
    // scroll to the element 
    $("body").scrollTop(pos - height); 
    // suppress default 
    return false; 
})​ 

See it in action here

0
/* START --- scroll till anchor */ 
     (function($) { 
      $.fn.goTo = function() { 
        var top_menu_height=$('#div_menu_header').height() + 5 ; 
        //alert ('top_menu_height is:' + top_menu_height); 
        $('html, body').animate({ 
         scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px' 
        }, 500); 
        return this; // for chaining... 
      } 
     })(jQuery); 

     $(document).ready(function(){ 

      var url = document.URL, idx = url.indexOf("#") ; 
      var hash = idx != -1 ? url.substring(idx+1) : ""; 

      $(window).load(function(){ 
      // Remove the # from the hash, as different browsers may or may not include it 
      var anchor_to_scroll_to = location.hash.replace('#',''); 
      if (anchor_to_scroll_to != '') { 
       anchor_to_scroll_to = '#' + anchor_to_scroll_to ; 
       $(anchor_to_scroll_to).goTo(); 
      } 
      }); 
     }); 
    /* STOP --- scroll till anchror */ 
相关问题