JQuery (JavaScript) to get the text width (display length)

Source: Internet
Author: User

Today, I encountered the problem of obtaining the text width. After a long time, I finally found a method on a foreign website, but I couldn't use it directly. So I modified it and successfully used it in the project, here we will share with you.

First, add a sub-tag at the end of the body Tag:

Test

Then add the corresponding css code:

# Rility {visibility: hidden; white-space: nowrap; font-size: 24px ;}

Next, add the function to get the text width in the String prototype, and add the following code to the js Code:

String. prototype. equalallength = function () {var r0000=$ ("# r0000"); r0000. text (this); return r0000[ 0]. offsetWidth ;}

Finally, you can call it where you need to obtain the text width. For example:

Var text = "test"; var len = text. visualLength ();


The main idea is to add a hidden tag. After each value is assigned to the tag, the text width is obtained by obtaining the length of the tag. Note that only labels added to the DOM can obtain the length.


If you feel helpful to yourself, I hope you can help me with it. Thank you :) my blog: Sorry!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.