使用 JavaScript 计算文本宽度 [英] Calculate text width with JavaScript

查看:22
本文介绍了使用 JavaScript 计算文本宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JavaScript 来计算字符串的宽度.这可能不需要使用等宽字体吗?

如果它不是内置的,我唯一的想法是为每个字符创建一个宽度表,但这很不合理,尤其是支持 Unicode 和不同的字体大小(以及与此相关的所有浏览器).

解决方案

创建具有以下样式的 DIV.在 JavaScript 中,设置要测量的字体大小和属性,将字符串放入 DIV,然后读取 DIV 的当前宽度和高度.它将拉伸以适应内容,并且大小将在字符串渲染大小的几个像素内.

var fontSize = 12;var test = document.getElementById("Test");test.style.fontSize = fontSize;var height = (test.clientHeight + 1) + "px";var width = (test.clientWidth + 1) + "px"console.log(height, width);

#Test{位置:绝对;可见性:隐藏;高度:自动;宽度:自动;空白:nowrap;/* 感谢 Herb Caudill 的评论 */}

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting Unicode and different type sizes (and all browsers for that matter).

解决方案

Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.

var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"

console.log(height, width);

#Test
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; /* Thanks to Herb Caudill comment */
}

<div id="Test">
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>

这篇关于使用 JavaScript 计算文本宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆