Home>Article>Web Front-end> How to get the width of text in jQuery? Method introduction

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

青灯夜游
青灯夜游 forward
2020-11-23 17:57:42 3329browse

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:

  

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; };

3. Use js to call this method:

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

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete