Today I encountered the problem of getting the text width. After searching for a long time, I finally found the method on a foreign website, but it couldn't be used directly, so I modified it and successfully used it in the project. I will share it with you here.
First add a sub-tag at the end of the body tag:
test
Then add the corresponding css code:
#ruler {
visibility: hidden;
white-space: nowrap;
font-size: 24px ;
}
Next, directly add the function to obtain the text width in the String prototype, and add the following code to the js code:
String.prototype.visualLength = function()
{
var ruler = $("# ruler");
ruler.text(this);
return ruler[0].offsetWidth;
}
Finally, just 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 label, and each time a value is assigned to the label, the text width is obtained by getting the length of the label. It should be noted that only tags that have 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:)