У меня есть строка, содержащая много текста, text в моем файле JavaScript. У меня также есть элемент div # container , стилизованный (с использованием отдельного CSS) с потенциально нестандартным line-height
, font-size
, font -face
и, возможно, другие. Он имеет фиксированную высоту и ширину.
Я ' Я хочу получить максимальное количество текста, которое может поместиться в контейнер div # без какого-либо переполнения из строки. Как лучше всего это сделать?
Это должно иметь возможность работать с текстом, отформатированным с помощью тегов, например:
<strong>Hello person that is this is long and may take more than a</strong>
line and so on.
В настоящее время у меня есть плагин JQuery, который работает с обычным текстом, код следующий:
// returns the part of the string that cannot fit into the object
$.fn.func = function(str) {
var height = this.height();
this.height("auto");
while(true) {
if(str == "") {
this.height(height);
return str; // the string is empty, we're done
}
var r = sfw(str); // r = [word, rest of String] (sfw is a split first word function defined elsewhere
var w = r[0], s = r[1];
var old_html = this.html();
this.html(old_html + " " + w);
if(this.height() > height)
{
this.html(old_html);
this.height(height);
return str; // overflow, return to last working version
}
str = s;
}
}
ОБНОВЛЕНИЕ:
Данные выглядят так:
<ol>
<li>
<h2>Title</h2>
<ol>
<li>Character</li>
<ol>
<li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
<li>Line two can be separated from line one, but not from itself</li>
</ol>
</ol>
<ol>
<li>This can be split from other</li>
<ol>
<li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
<li>Line two can be separated from line one, but not from itself</li>
</ol>
</ol>
</li> <li>
<h2>Title</h2>
<ol>
<li>Character</li>
<ol>
<li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
<li>Line two can be separated from line one, but not from itself</li>
</ol>
</ol>
<ol>
<li>This can be split from other</li>
<ol>
<li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
<li>Line two can be separated from line one, but not from itself</li>
</ol>
</ol>
</li>
</ol>