[thelist] counting rendered lines of text
Jonathan Snook
jonathan.snook at gmail.com
Thu Jun 14 12:36:48 CDT 2007
On 6/14/07, sbeam <sbeam at syxyz.net> wrote:
> Say you have a container of a fixed width with some text in it. Is there
> any way to count the number of lines in the text, as rendered?
Here's a quick script I threw together. Keep in mind, it doesn't
account for padding, margins, borders or inline elements that exceed
the line height and I haven't tested it in anything but Firefox. I did
a variation that simply truncated it word by word until it fell under
the appropriate line height.
Hopefully this gets you going in the right direction.
/*
el = the element I want to shorten
lines = the # of lines to shorten to
*/
function shorten(el, lines)
{
var height, tmp;
// determine line height by putting a space into the
// container and grabbing the height of the container
tmp = el.innerHTML;
el.innerHTML = ' ';
height = el.offsetHeight;
el.innerHTML = tmp;
var fullheight = el.offsetHeight;
// find out how many lines of text I have
var divisor = fullheight / height;
tmp = el.innerHTML.substr(0, el.innerHTML.length / divisor * lines);
el.innerHTML = tmp.substr(0, tmp.lastIndexOf(' ')) + '…';
}
More information about the thelist
mailing list