【问题标题】:Offsetting scrollTop偏移滚动顶部
【发布时间】:2012-08-12 04:38:36
【问题描述】:

我有以下sn-p

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

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

我怎样才能做到这一点?

我在 offset() 中添加了 paddingTop:5 但这不是我们想要的结果。

【问题讨论】:

  • ... 你想得太远了。为什么不把 5 加到 $('#menu').offset().top 上?

标签: jquery html scroll offset


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    此代码已修复它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多