Get text block sizes using JavaScript, not the size of the `getBoundingClientRect` container

I want to get the size of the text inside the container. Consider the general case when the container has indents and borders.

The problem is that getBoundingClientRect returns the size of the text PLUS of the left border and indentation in case of text overflow. Otherwise, it returns only the size of the border field of the container.

enter image description here

+6
source share
3 answers

You can get the width if you create a placeholder with all the same text formatting options and find its width.

For example, I will create a div with a .hidden class that has the same attributes as the original div.

 div.container { font-size: 16px; } div.hidden { font-size: 16px; display: none; } 

Then, using jQuery, copy the contents of .container to .hidden and find the width of .hidden :

 $(function(){ $("div.container").each(function(){ $("body").append("<div class='hidden'>"+$(this).html()+"</div>"); var width = $("div.hidden").width(); $("div.width").html("Actual width: "+width+"px"); $("div.hidden").remove(); }); }); 

Jsfiddle

+2
source

Interesting! You can use javascript to clone text inside an empty element behind the frame, which has 0 padding / margin / border. Then you can get the width of this element.

 var txt = document.getElementById('fixed').innerHTML, clone = document.getElementById('clone'); clone.innerHTML = txt; var width = clone.offsetWidth; document.getElementById('output').innerHTML = width; 
 #fixed { width: 8em; height: 8em; border: .5em solid red; } #clone { margin: 0; padding: 0; border: 0; position: fixed; left: -9999px; } 
 <div id="fixed">asdfkjahsdflkahjsdflkjhasdljfhalsdkjfhalsdkjfhalsdkjfhalksdhjflasd</div> <div id="clone"></div> Width of text: <span id="output"></span> 
+2
source

The people who answered here came up with the brilliant idea of ​​wrapping text around a <div> with zero margin , border and padding ;

I just developed the idea further. I put a div inside the container, making the text in the same style as without a wrapper.

Jsfiddle

This solution will work almost everywhere. This may be broken in a not very encouraging way of writing CSS, for example

 .container div b { padding: 5px; /* firing only when test is run */ } 

If you don’t encode CSS in your project like this, you are fortunate to use my snippet)

0
source

Source: https://habr.com/ru/post/979731/


All Articles