使用jq获取文字的宽度

获取字符串的长度很简单,但是如何获取一个字符串的字体宽度却是一个不太好操作的问题,今天查阅了许多资料,终于找到了解决方法:

1.首先,需要添加一个标签,HTML代码如下:

<body>
<span></span>
</body>

2.接下来直接在String的原型中添加获取文字宽度的函数,在js代码中加入以下代码即可:

String.prototype.visualLength = function()
        {
            let ruler = $("span");
            ruler.text(this);
            return ruler[0].offsetWidth;
        };

 3.使用js来调用这个方法:

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

  效果如下:

记得要引入jq,博主使用的是es6

时间: 2024-08-29 22:47:04

使用jq获取文字的宽度的相关文章

android获取文字宽度

Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setColor(Color.WHITE); // Define the string. String displayText = “Hello World!”; // Measure the width of the text string. float textWidth = mTextPaint.measureText(displayText); android获

Javascript 获取dom的宽度 随笔一

javascript 中 offsetWidth 获得的并不是 真实的宽度 不等于 style.width ;offetWidth 实际上获得的是物体的盒模型尺寸. 包括 border padding 等尺寸.obj.style.width 只能获得行间样式宽度,不能获得样式表中的样式中的宽度 获取不在行间宽度的方法 function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; /*仅支持IE*

Js与Jq 获取浏览器和对象值的方法

JS and Jquery 都能获取页面元素的宽度,高度和相对位移等数值,那他们之间能相互转换或替代吗,写法又有哪些差异呢?本文将详细为你介绍. 1.Js获取浏览器高度和宽度document.documentElement.clientWidth ==> 浏览器可见区域宽度 document.documentElement.clientHeight ==> 浏览器可见区域高度 document.body.clientWidth ==> BODY对象宽度 document.body.cli

【整理】原生js和jQ获取窗口宽高及滚动条的方法和函数

原生js和jQ获取窗口宽高及滚动条的方法和函数 一.原生js获取 1.实际宽高(不包括工具栏,滚动条的视口高度,ie6.7.8不支持) window.innerHeight window.innerWidth 2.显示屏宽高 screen.height screen.width 3..显示屏宽高(除windows任务栏之外的高度)屏幕可用工作区 screen.avaiHeight screen.availWidth 4.网页可见区域宽高 document.body.clientWidth doc

react-native 获取组件的宽度和高度

react-native 获取组件的尺寸有两种方式,第一种方式使用元素自身的onLayout属性去获取,但是这种方式有一个局限性,就是只有在初次渲染的时候才会触发这个函数,而且此种方法获取的是组件相对于父组件的位置坐标.如果我们需要随时都可以去获取组件的尺寸或者相对于屏幕的位置坐标时,这种方式并不适合. 那么这里我们就来看下第二种方式,使用react-native中的findNodeHandle和UIManager来获取组件的尺寸: import { findNodeHandle, UIMana

JS兼容方式获取浏览器的宽度

<script type="text/javascript"> //need to wait until onload so body is available window.onload = function(){ function getWindowWidth(){ if (window.innerWidth){ return window.innerWidth; } else if (document.documentElement.clientWidth){ ret

js获取页面的宽度

JS如何获取屏幕浏览器网页高度宽度网页可见区域宽:document.body.clientWidth网页可见区域高:document.body.clientHeight网页可见区域宽:document.body.offsetWidth (包括边线的宽)网页可见区域高:document.body.offsetHeight (包括边线的宽)网页正文全文宽:document.body.scrollWidth网页正文全文高:document.body.scrollHeight网页被卷去的高:docume

安卓获取屏幕的宽度与高度

获取屏幕的宽度与高度有以下几种方法: 1.WindowManager wm = (WindowManager) getContext()                     .getSystemService(Context.WINDOW_SERVICE);        int width = wm.getDefaultDisplay().getWidth();      int height = wm.getDefaultDisplay().getHeight();   2.Window

如何在onCreate方法中获取视图的宽度和高度

你可以通过视图的getWidth()和getHeight()来获取视图的宽度和高度. 但是,可能会让你失望的是,如果你直接在onCreate方法内调用这两个函数,你会的到0. 为什么呢? 这是因为,当onCreate被调用的时候,视图的内容正在被LayoutInflater来填充xml布局. 这个过程会填充布局,但是暂时不会设置视图的大小. 那么视图到底什么时候获得自己的大小尺寸呢? 实际上是在Layout以后,而layout又是在onCreate调用以后. 那么,如果我们要在onCreate方