1

Line f.e.:

    <p style="width: 300px;">asdasd sa das d asd a sd as das dasdasdasdasd saddasdasdasdasd asdasdsd</p>

The width of P is 300px but each of the lines is smaller. I need to calculate it for each line. Screen: multiline block

Kypaku
  • 21
  • 3

2 Answers2

1

Maybe too late but, I had the same request, and I thought a solution. When you make a selection to a div, you can get the bounding rects, of every selection box, so, if you have multiple line you get the width and the position of every line.

window.getSelection().selectAllChildren(document.querySelector("p#element"));
var selection = window.getSelection();
var range = selection.getRangeAt(0); 
var rects = range.getClientRects();
console.log(rects);
Víctor Quilón
  • 109
  • 1
  • 9
0

I do not know js way but you can use jquery for that:

   <p id="demo" style="white-space:pre">
    Line 1

    Line 2

    Line 3

    Line 4 Blah

    Line 5
    </p>

JQUERY:

  $(function(){
var text =  $.trim($('#demo').text());
// this may vary browser to browser...
var text_w_no_empty_lines = text.replace(/[\r\n]+/g, '\n');
var lines = text_w_no_empty_lines.split('\n');
// line number you want  total - 1
var line_5 = lines[4];
// .tick { white-space:nowrap;display:inline-block;display:none }
alert( $('<p class="tick">').html(line_5).appendTo('body').width() )
}
);