Home > Web Front-end > JS Tutorial > body text

How to get the width of text in jQuery? Method introduction

青灯夜游
Release: 2020-11-23 17:57:42
forward
3351 people have browsed it

How does jQuery get the width of text? The following article will introduce to you how to use jq to obtain the text width. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to get the width of text in jQuery? Method introduction

Related recommendations: "jq视频"

Getting the length of a string is very simple, but how to get the font of a string Width is a problem that is not easy to operate. I checked a lot of information today and finally found a solution:

1. First, you need to add a tag. The HTML code is as follows:

<body>
<span></span>
</body>
Copy after login

2 .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()
        {
            let ruler = $("span");
            ruler.text(this);
            return ruler[0].offsetWidth;
        };
Copy after login

3. Use js to call this method:

  let text = "分";
  let len = text.visualLength();
  console.log(len);
Copy after login

Effect As follows:

Remember to introduce jq, the blogger is using es6

For more programming related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to get the width of text in jQuery? Method introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!