根据元素高度拆分段落的最有效方法

Most efficient way to split paragraph based on element height

本文关键字:有效 方法 分段落 拆分 元素 高度      更新时间:2023-09-26

将很长的HTML段落元素动态拆分为给定高度的较小段落的最有效方法是什么?

下面的函数(jQuery)递归地从文本中一次切出一个单词,检查新的长度,并在文本分解成可接受的小块时停止。

function split_par(element, max_height)
{
  if (element.height() <= max_height)
    return;
  var array = element.text().split(" ");
  var pos = 0;
  while (element.height () > max_height)
  {
    pos -= 1;
    element.html("<p>" + array.slice(0,pos).join(" ") + "</p>");
  }
  var next_par = element.clone();
  next_par.html("<p>" + array.slice(pos).join(" ") + "</p>");
  $('body').append(next_par);
  split_par(next_par, max_height);
}

这是低效的,需要很长时间,但这是我找到的最可靠的方法。我相信有更好的方法。我也不熟悉Javascript或jQuery,所以任何关于代码的一般提示将不胜感激。

也许将

文本放在容器元素(例如divs)中并使用Jquery Masonry之类的东西就可以了。