我想用JavaScript来计算字符串的宽度。不用使用等宽字体,这是可能的吗?
如果它不是内置的,我唯一的想法是为每个字符创建一个宽度表,但这是非常不合理的,特别是支持Unicode和不同的字体大小(以及所有的浏览器)。
发布于 2008-09-22 23:40:58
创建具有以下样式的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>
发布于 2011-02-19 07:39:26
这里有一个我在没有例子的情况下拼凑起来的。看起来我们都在同一条船上。
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div></div>')
.text(this)
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
使用它很简单:"a string".width()
**增加了white-space: nowrap
,可以计算宽度大于窗口宽度的字符串。
发布于 2010-10-27 19:01:48
这对我很有效..。
// Handy JavaScript to measure the size taken to render the supplied text;
// you can supply additional style information too if you have it.
function measureText(pText, pFontSize, pStyle) {
var lDiv = document.createElement('div');
document.body.appendChild(lDiv);
if (pStyle != null) {
lDiv.style = pStyle;
}
lDiv.style.fontSize = "" + pFontSize + "px";
lDiv.style.position = "absolute";
lDiv.style.left = -1000;
lDiv.style.top = -1000;
lDiv.innerHTML = pText;
var lResult = {
width: lDiv.clientWidth,
height: lDiv.clientHeight
};
document.body.removeChild(lDiv);
lDiv = null;
return lResult;
}
https://stackoverflow.com/questions/118241
复制相似问题