2012-08-12 114 views
1

我有下面的代码片段抵消scrollTop的

$('html,body').animate({scrollTop: $('#menu').offset().top}, 'slow'); 

上的链接的点击,我想浏览器从附近显示#menu div的顶部。我希望它在菜单之前显示几行像素。

我该如何做到这一点?

我已添加paddingTop:5 offset(),但这不是所需的结果。

+1

...你在想太多。为什么不把5添加到'$('#menu')。offset()。top'? – Kiruse 2012-08-12 04:42:41

回答

14

只是减去你$('#menu').offset().top想要的任何金额:

$('html,body').animate({ 
    scrollTop: $('#menu').offset().top - 5 // or 10 
}, 'slow'); 

这里的小提琴:http://jsfiddle.net/qVWuv/

0

此代码已固定它。

$(function() { 
     $('a').click(function() { 
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(0) +']'); 
      if (target.length) { 
      $('#content').animate({ 
       scrollTop: target.offset().top - 15 
      }, 1000); 
      return false; 
      } 
     } 
     }); 
    });