偏移scrollTop

时间:2012-08-12 04:38:37

标签: jquery html scroll offset

我有以下代码段

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

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

我怎样才能做到这一点?

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

2 个答案:

答案 0 :(得分:15)

只需从$('#menu').offset().top

中减去您想要的金额
$('html,body').animate({
    scrollTop: $('#menu').offset().top - 5 // or 10
}, 'slow');

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

答案 1 :(得分: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;
          }
        }
      });
    });