admin管理员组

文章数量:1326338

Consider a simple html element as

<div id="test">
a long text without line break
</div>

The browser will create lines based on the glyph and font sizes. After text arrangement by the browser (e.g. depending on the window width), how to get the lines of the text by JavaScript?

For example:

  1. How to get the total number of lines
  2. How to get the first line as appeared in the current window?
  3. How to get the nth line?

Consider a simple html element as

<div id="test">
a long text without line break
</div>

The browser will create lines based on the glyph and font sizes. After text arrangement by the browser (e.g. depending on the window width), how to get the lines of the text by JavaScript?

For example:

  1. How to get the total number of lines
  2. How to get the first line as appeared in the current window?
  3. How to get the nth line?
Share Improve this question edited Jan 6, 2014 at 14:16 Ahmed Hamdy 2,9271 gold badge19 silver badges23 bronze badges asked Jan 6, 2014 at 14:11 GooglebotGooglebot 15.7k45 gold badges144 silver badges247 bronze badges 3
  • 1 what constitutes a line? – Prisoner Commented Jan 6, 2014 at 14:13
  • I doubt 2 and 3 can be solved. – Prinzhorn Commented Jan 6, 2014 at 14:14
  • 1 @Prisoner what we currently see on the screen! The lines that browser creates to show a long text. – Googlebot Commented Jan 6, 2014 at 14:16
Add a ment  | 

3 Answers 3

Reset to default 4

No, there is no API that gives you access to the rendered text after layout has occurred. The only way to approximate this is pretty hacky, i.e. add words into a container one at a time and see when it changes height. See this related question:

detecting line-breaks with jQuery?

Yeah, who'd have thought it, even jQuery doesn't do this! ;-)

2 easy solutions and a extremely hard one.

1 Formatting the text.

Inside a pre & textContent

html

<pre>hello
hello1
hello2</pre>

js

document.getElementsByTagName('pre')[0].textContent.split('\n')

http://jsfiddle/gq9t3/1/


2 Adding br's

Inside a div with br & textContent

html

<div>hello<br>hello1<br>hello2<br>pizza</div>

js

document.getElementsByTagName('div')[0].innerHTML.split('<br>')

http://jsfiddle/gq9t3/4/


To much trouble

css

div{width:100px;line-height:20px;}

html

<div>hello dfgfhdhdgh fgdh fdghf gfdh fdgh hello1gfhd gh gh dfghd dfgh dhgf gf g dgh hello2</div>

js

document.getElementsByTagName('div')[0].offsetHeight/20

easy way to find the number of lines but you need to calculate the text width to find the corresponding line content.

http://jsfiddle/gq9t3/3/

I was attempting to style the first line of text, but text-transform:uppercase messed it up. http://zencode.in/lining.js/ helped with addressing the first line (responsively!), so perhaps this library will assist with your issue too.

本文标签: How to get nth line of a text by JavaScriptStack Overflow