简体   繁体   中英

How to get the width of a line of multi-line text use Javascript

Line fe:

 <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

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() )
}
);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM