jquery calculates text width and input tag implementation based on dynamic adaptive width of input characters

Source: Internet
Author: User

jquery calculates the width of the text by using the <pre> tag provided by the HTML, adding the <pre> tag to the DOM dynamically, the content of the tag is to test the length of the text, get the length and then delete the <pre> tag just added, thereby advisable to the approximate length of the text. Why use labels instead of other tags, then look at the features of the <pre> tag: The pre element can define preformatted text. Text that is surrounded by the pre element usually preserves spaces and line breaks, and the text is rendered as equal-width fonts. A common application of <pre> tags is to represent the source code of the computer. Note that it is best not to have other tags in the text when calculating the length of the text. Here is the implementation code:

// Get text width    var function (text) {         var sensor = $ (' <pre> ' + text + ' </pre> '). CSS ({display: ' None '});         $ (' body '). append (sensor);          var width = sensor.width ();        Sensor.remove ();          return width;    };

With this function above, the input tag is easy to implement based on the dynamic adaptive width of the entered character:

// Input width Adaptive    function () {        $ (this). Width (textWidth ($ (this). Val ()));    }); 

jquery calculates text width and input tag implementation based on dynamic adaptive width of input characters

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.