如何计算富文本的总行数

时间:2019-03-26 03:36:08

标签: javascript

我得到了一个由富文本编辑的字符串,现在我需要显示,当它超过三行时,我需要隐藏其余的行。但是我不知道如何获取富文本格式的总行数。由于它具有各种标签,例如p,h1,h1,span ... 也许您得到如下字符串:

Title

description description description description description description description description description description description description description description description descriptiondescription description description description description description description description description description description description...

  1. and some others order list
  2. and some others order list
enter image description here

2 个答案:

答案 0 :(得分:0)

您实际上无法计算行数,因为您不知道用户输入的内容可能与输出的屏幕尺寸有关。 <H1>将比<P>占用更多的垂直空间。用户可能会放大或缩小浏览器文本。

使用CSS会更好。

 .limit-text-2-rows {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-height: 21px;
    max-height: 48px;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
 }

答案 1 :(得分:0)

我确信这是可能的,但这很棘手。 在2013年的某个地方,我编写了两个函数来对inline元素(任何inline,也包括inline-block)中的行进行计数,并编写了一个函数(相当hacky但可用)将省略号应用于HTML元素。

计算行数的功能很短: (从老板上线的旧代码存储库中挖出:https://github.com/WebHare/designfiles/blob/master/wh.layout.measure/wh.layout.measure.js

/** @short count the amount of lines within an inline element
*/
$wh.countLinesInElement = function countLinesInElement(node)
{
  var rects = node.getClientRects();

  // Firefox returns a rects for each line,
  // Chrome can return multiple rects per line
  var lines = 0;
  for (var idx = 0; idx < rects.length; idx++)
  {
    if (idx == 0 || rects[idx-1].top != rects[idx].top)
      lines ++;
  }
  return lines;
}

注意事项/问题:

  • 它仅对内联元素中的行计数(我也有一个使用范围内的rect的版本,我不记得那个版本是否适用于非内联元素)。
  • 根本没有在flexbox,多列或网格布局上进行测试(2013年它们尚未准备好在实际站点上使用)
  • Chrome每行返回了多个rect,所以我猜(未经测试)这意味着某些CSS属性可能会影响顶部并混淆此简单函数

此方法可用于查找需要将省略号应用于哪个元素。您将需要遍历元素(如果子元素是块元素,则需要对其进行遍历)。当您发现将溢出的元素时,可以应用-webkit-line-clamps(奇怪的是,除IE支持外,如今所有浏览器都支持)。 当然,这一切都有些麻烦,因此,是否可行和是否值得取决于您要使用它的目的。

我提到的另一项我对多行文本应用多行省略号的功能只是使用了边界客户端矩形,并试图缩短文本,直到其适合指定的最大空间。并非如此友好的性能,因此每次调整文档大小时,都需要采用重用回流的方式来应用省略号。 (它也使用了MooTools,但是它将用于更改为纯Javascript)。如果您想查看,请在这里:

https://github.com/WebHare/designfiles/blob/master/wh.layout.applyellipsishtml/wh.layout.applyellipsishtml.js