This is difficult, but can be done even if there is no given line height or other style. This is due to a bunch of moving parts.
First create a "sacrificial" container <div> . Fill it with the known number of lines of text, one character at a time and place it far beyond the screen:
// calculate height per line $calcdiv = $('<div/>').css({ width: '50px', position: 'absolute', // don't affect layout left: '-2000px' // position far off=screen }).html('A<br />B<br />C<br />D<br />E'); // add five lines $('body').append( $calcdiv ); // make the browser render it var lineHeight = $calcdiv.height()/5; // average height per line
Now we know the approximate row height in pixels displayed by this browser. Let's pay attention to the field that needs to be measured:
$origDiv = $('div#div_to_measure'); $measureDiv = $origDiv.clone(); // clone it $measureDiv.css({ position: 'absolute', left: '-1000px', // position far off-screen height: 'auto' // let it grow to its natural full height }); $('body').append( $measurediv ); // add it to the DOM, browser will render it
... and now we know the approximate number of lines in the field, if allowed to reach its natural sizes displayed by the browser:
var numLines = $measureDiv.height() / lineHeight;
We need clone() , because the source field that needs to be measured can have its height limited by the current styles and page layout.
Now a little cleanup:
$calcdiv.remove(); $measureDiv.remove();
Here is an example: http://jsfiddle.net/redler/FuWue/
Ken redler
source share