jQuery 偏移滚动顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11919766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:05:14  来源:igfitidea点击:

Offsetting scrollTop

jqueryhtmlscrolloffset

提问by InvalidSyntax

I have the following snippet

我有以下片段

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

On click of a link I would like the browser to display from nearthe top of the #menu div. I would like it display just few pixels lines before the menu.

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

How can I achieve this?

我怎样才能做到这一点?

I have added paddingTop:5 to offset() but this is not the desired result.

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

回答by Joseph Silber

Just subtract whatever amount you want from $('#menu').offset().top:

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

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

Here's the fiddle: http://jsfiddle.net/qVWuv/

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

回答by user3189826

This code has fixed it.

此代码已修复它。

$(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;
          }
        }
      });
    });