【问题标题】:jQuery innerHeight() returning wrong valuejQuery innerHeight() 返回错误的值
【发布时间】:2016-11-02 05:47:16
【问题描述】:

我正在使用CSS Tricks Smooth Scrolling 使我的菜单链接滚动到页面的不同部分。我添加了- jQuery('#masthead').height() 来说明固定导航栏的高度。但是,当我单击一个菜单项并且页面滚动到该点时,菜单栏和它滚动到的位置之间似乎有一个额外的像素。 See what I mean here.

这是我的 jQuery 代码:

jQuery(function() {
  jQuery('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = jQuery(this.hash);
      target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        jQuery('html, body').animate({
          scrollTop: target.offset().top - jQuery('#masthead').innerHeight()
        }, 1000);
        return false;
      }
    }
  });
});

【问题讨论】:

  • 对我来说很好......

标签: jquery


【解决方案1】:

innerHeight() 函数不会添加填充或边框,您应该改用outerHeight(),然后才能按预期工作。

jQuery 代码应该是:

    jQuery(function() {
  jQuery('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = jQuery(this.hash);
      target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        jQuery('html, body').animate({
          scrollTop: target.offset().top - jQuery('#masthead'). outerHeight()
        }, 1000);
        return false;
      }
    }
  });
});

【讨论】:

  • 谢谢,但它有完全相同的问题,即使我使用 outerHeight()! :(
  • “关于帮助”和“联系方式”。他们都向下滚动到我想要的上方1px。例如,如果您点击“联系方式”,它会向下滚动到联系方式,您可以在上面的“关于帮助”部分的菜单下方看到一条 1 像素的白线。
  • 我只能在联系时看到错误,当我检查代码时,我看到你有#contact { padding :1px; } ,为什么要在那里添加填充?
  • 我必须添加它以使#contact 占据整个空间。没有它,它会适合内容,滚动效果会更差(取消选中开发工具中的 padding: 1px 并尝试在菜单中单击以了解我的意思)。我认为这不是导致问题的原因,因为应用了 { box-sizing: border-box }。你怎么看?
猜你喜欢
  • 1970-01-01
  • 2020-11-10
  • 2012-05-22
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多