Home >Web Front-end >JS Tutorial >jQuery (js) gets text width (display length) sample code_jquery

jQuery (js) gets text width (display length) sample code_jquery

WBOY
WBOYOriginal
2016-05-16 17:06:001126browse

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:

Copy the code The code is as follows:

test

Then add the corresponding css code:
Copy the code The code is as follows:

#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:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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:)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn