JQuery of js gets the text width of display length sample code

  • 2020-03-30 01:11:00
  • OfStack

Today, I encountered the problem of obtaining the text width. After searching for a long time, I finally found the method on a foreign website. However, I could not use it directly.

Start by adding a subtag at the end of the body tag:
<span id="ruler">test</span> 

Then add the corresponding CSS code:
#ruler { 
visibility: hidden; 
white-space: nowrap; 
font-size: 24px; 

Next, directly add the function to get the text width in the prototype of String, and add the following code in the js code:
String.prototype.visualLength = function() 
var ruler = $("#ruler"); 
return ruler[0].offsetWidth; 

Finally, you can call it where you need to get the text width, for example:
var text = "test"; 
var len = text.visualLength(); 

The main idea is to add a hidden tag and get the text width by getting the length of the tag after each assignment. Note that only tags that have already been added to the DOM can get the length.

If you think it is helpful to you, I hope you can help me. Thank you

Related articles: