2012-08-12 121 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; 
      } 
     } 
     }); 
    });