PDA

View Full Version : Determining text lines in a div


sirrobert
06-25-2007, 07:28 PM
Hey everyone. I've got some DIV elements containing arbitrary HTML that is entirely text (some of the childNodes are textNodes, some are strong or em tags containing textNodes, some are divs or spans containing textNodes, etc.).

It's pretty easy to get the entire text content of the div, but I'm having a tough time trying to figure out how to grab sub-sets of the text content spatially.

That is, let's say I've got a div with a string of text that breaks into four lines (because of the width of the div, etc). How can I capture just the second line, or just the third line, etc?

Is there some way to determine at which character (or word, or textNode, or ...?) the lines break? Is there some way to determine what is the first or last character of a line?


For the sake of simplicity, let's assume I have a div:
var dv = document.getElementById('myDiv');

and dv has the several lines of text (in arbitrary HTML).

Thanks,
sirrobert

tripy
06-26-2007, 01:56 PM
There is no way of doing this, as far as I know.

As the text is being rendered, it can render really differently on your users screens.
I know a lady with really bad eyes who have a 300% font increasing to read what is on her screen...

In that case, you would nearly have just 1 word per line...

What you can do to avoid it, is to have as many textnodes as lines you want, and to iterate through them. That will partially solve the problem.

rnd me
07-20-2007, 05:18 PM
this is very tricky indeed.

a way that worked for me back in vb6 was to clone the font settings of the text, and the size settings of the container. then, in a loop i would rebuild the string; adding a char to the end of the string, one at a time. monitoring the height of the container after each character addition, one can easily identify the "straw the broke the camel back'. ie, when the height > the last height, there is your line break.

all the needed properties are dom-accessable, and are props of the container itself, not the container's style property.

good luck.