【问题标题】:height() not returning correct height on elementheight() 没有在元素上返回正确的高度
【发布时间】:2014-09-22 05:06:56
【问题描述】:

我正在尝试通过将框高度调整为溢出内容高度来修复溢出的浮动内容,但它似乎并没有起到作用。

            if ( $('.content-right').outerHeight() > $('.content-right').parent().parent().height() ) {
                $('.content-right').parent().parent().height($('.content-right').outerHeight(true));
            }
            console.log('Box Height: ' + $('.content-right').parent().parent().height());
            console.log('Content Height: ' + $('.content-right').height() );

这将输出

Box Height: 599
Content Height: 594 

这是不正确的,因为在下面的示例中 div 显然要大得多。有任何想法吗?

图片形式的问题区域:http://prntscr.com/4p1obb

【问题讨论】:

  • 如果你仔细阅读文档:api.jquery.com/height 它写得很清楚:This method does not accept any arguments.
  • 不要使用.parent().parent(),而是看看api.jquery.com/closest方法。
  • 另外,缓存元素你打算多次使用并且过度使用var $contRight = $('.content-right');
  • @RokoC.Buljan 这是此处编辑的错误。是 outerHeight(true) 没有一个 cmets 是针对这个问题和挑剔的。
  • 我不知道。我只是建议查看 you 提供的代码。你确定你得到了正确的元素吗?我看到你使用 class 选择器元素。可能会返回错误的吗?

标签: jquery height outerheight


【解决方案1】:

在旧版本中存在一个错误 jQuery outerHeight,如果您不传递参数,它将不会返回高度。同样如 cmets 中所建议的,您需要从 height() 中删除 true。

if ( $('.content-right').outerHeight(true) > $('.content-right').parent().parent().height() ) {
  $('.content-right').parent().parent().height($('.content-right').outerHeight(true));
}
console.log('Box Height: ' + $('.content-right').parent().parent().height());
console.log('Content Height: ' + $('.content-right').height() );

更新:

试试这个(上面提到的错误仍然存​​在,所以一定要输入一个参数)。下面的代码给了我 868 的高度。

var outerHeight = 0;
$('.content-right > *').each(function() {
  outerHeight += $(this).outerHeight(true);
});
console.log(outerHeight);

【讨论】:

  • 请缓存您的选择器!使用.closest('selector') 方法而不是不必要地嵌套.parent()
  • @Roko C. Buljan 优化 OP 的代码不是我的目标。我建议回答他的问题。你已经在上面的 cmets 中提出了这个建议,所以他可以自己做。
  • Roko,别再有偏见了。它与功能无关。这是个人意见。如前所述,它已从尝试调试的 vars 重写。谢谢,如页面所示,没有错误。返回的高度不正确
  • @manishie 该问题在图片中可见。 .content-right 比返回的结果大很多:prntscr.com/4p1obb
猜你喜欢
  • 2011-07-07
  • 2015-08-20
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2018-11-13
  • 1970-01-01
  • 2019-10-17
相关资源
最近更新 更多