Featured post
How to check for # of lines using jQuery -
example: div width of 30px words "this text". let's that, since width narrow, renders on page this:
this
is
text
(3 lines). there way in jquery tell how many lines takes render page? example, like, $("#container").linecount()
.
business purpose: if content exceeds number of lines, want manipulate scroll bar not appear, have fixed height, don't want mess overflow css prop.
thanks!
this tricky can done, if there no specified line-height or other style. involve bunch of moving parts.
first, build "sacrificial" container <div>
. fill known number of lines of text, 1 character each, , position far off-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 5 lines $('body').append( $calcdiv ); // make browser render var lineheight = $calcdiv.height()/5; // average height per line
now know approximate height of line, in pixels, rendered browser. turn our attention box measured:
$origdiv = $('div#div_to_measure'); $measurediv = $origdiv.clone(); // clone $measurediv.css({ position: 'absolute', left: '-1000px', // position far off-screen height: 'auto' // let grow natural full height }); $('body').append( $measurediv ); // add dom, browser render
...and know approximate number of lines in box if allowed attain natural dimensions rendered browser:
var numlines = $measurediv.height() / lineheight;
we have clone()
because original box measured may have height restricted current page styles , layout.
now cleanup:
$calcdiv.remove(); $measurediv.remove();
here's example: http://jsfiddle.net/redler/fuwue/
- Get link
- X
- Other Apps
Comments
Post a Comment