2

我有以下片段

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

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

我怎样才能做到这一点?

我已将 paddingTop:5 添加到 offset() 但这不是预期的结果。

4

2 回答 2

16

只需从中减去您想要的任何金额$('#menu').offset().top

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

这是小提琴:http: //jsfiddle.net/qVWuv/

于 2012-08-12T04:49:43.337 回答
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;
          }
        }
      });
    });
于 2014-08-22T12:31:34.713 回答