如果换行时有孤立的单词,jQuery不计算文本的正确高度

jQuery not calculating correct height of text if there is an orphaned word on line break

本文关键字:计算 文本 高度 jQuery 单词 换行 如果      更新时间:2023-09-26

如果你看看我正在开发的这个页面:http://dev.aaronpitts.ch/test/,你会看到三个绿色的按钮,每行写着'Find out more'。我试图让他们总是使用以下jQuery对齐:

var maxHeight = 0;
$(".same-height-inner").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(".same-height-inner").height(maxHeight);

.same-height-inner中的p块有一个20px的margin-bottom,但它不包括在。same-height-inner的高度中。此外,如果你在1024 x 768的屏幕上看这个,你会看到左手栏的文本在高度上得到了进一步的错误计算,因为它不包括孤立的单词,它被分割成一个新的行。我试过使用

outerHeight(true)

但是没有区别。我怎样才能做到以上几点呢?

您可以简单地将.find('p')添加到您的jQuery代码中,因此它将是:

var maxHeight = 0;
$(".same-height-inner").find('p').each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(".same-height-inner").height(maxHeight);

同样,如果你使用outerHeight(true),例如,我使用以下代码:

function calculateHeight($el) {
   var height = 0;
   $el.children().find('a').each(function() {
      height = height + $(this).outerHeight(true);
    });
   $el.data('oHeight', height);
}

好运。

这是因为paragraph元素比div元素大因为它是block元素中的内联元素,所以只需要在选择器

中包含p
$(".same-height-inner p").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(".same-height-inner").height(maxHeight);

你也可以将div设置为内联,这也可以解决问题,但可能会在网站的其他地方产生意想不到的后果。

.same-height-inner {
    display: inline-block;
}