Get css width from string

I have a line that I want to display on a dynamically transferred webpage. I want to be able to dynamically determine the css width needed to display this line, and then wrap it in an html element with the exact size to display it.

I am currently using javascript and dojo, so the answers using these two are good, but nothing else will work.

Details I think I should clarify. I want to display a string in an input field, therefore not as simple as a div (I think at least)

+4
source share
4 answers

If you want to set the length of <input> to display all characters in a string, you can set it like this:

 var myString = "abcdefg"; // this is what got input dynamically var myInputElement = document.getElementById('someInput'); myInputElement.size = myString.length; 
+4
source

Since usually a good measure of characters is em.

You can do it:

 var element = Document.getElementById("ID"); element.style.length = element.value.length + " em"; 
+1
source

You must remember that before calculating the pixel width of a string in relation to this character account, you need to somehow know the metrics of the font used.

If then you had to take the input string, wrap it in <span>, paste it into the document, calculate the width of the element, and then remove the range and add the value to the final destination, which you will have a pretty decent projection of the estimated width, while your range has the same font style rules as the destination element.

If you want to get really fantasy and technical information about this, then the HTML 5 <canvas> tag is your friend.

A good article to better understand the complexity of font metrics in javascript, which will also help you solve this problem: http://mudcu.be/journal/2011/01/html5-typographic-metrics/#measure

+1
source

you can create an element and put some callback in this load event

 var span = $("<span/>").text("your input").load(function(e){ console.log($(this).width()); }); 

this way you can get the current width. do not define the width of the span element and do not float.

-one
source

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


All Articles