我想使用JavaScript计算字符串的宽度。 是否可以不必使用等宽字体?
如果不是内置的,我唯一的想法就是为每个字符创建一个宽度表,但这是非常不合理的,特别是支持Unicode和不同类型的大小(以及与此相关的所有浏览器)。
#1楼
创建具有以下样式的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 { position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; /* Thanks to Herb Caudill comment */ }
<div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ </div>
#2楼
<span id="text">Text</span>
<script>
var textWidth = document.getElementById("text").offsetWidth;
</script>
只要<span>标记没有应用其他样式,它就应该起作用。 offsetWidth将包括任何边框的宽度,水平填充,垂直滚动条宽度等。
#3楼
ExtJS javascript库具有一个称为Ext.util.TextMetrics的出色类,该类“为文本块提供精确的像素测量,以便您可以精确确定给定的文本块的高度和宽度(以像素为单位)”。 您可以直接使用它,也可以查看其源代码以查看其完成方式。
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
#4楼
您可以使用画布,因此您不必处理CSS属性:
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20pt Arial"; // This can be set programmaticly from the element's font-style if desired
var textWidth = ctx.measureText($("#myElement").text()).width;
#5楼
试试这个代码:
function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto";
obj.style.height = "auto";
var Ret = obj.getBoundingClientRect();
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px";
return Ret;
}
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3161750