我过去曾使用 jQuery 完成此操作。您可以像这样测量一段文本的大小:
// txt is the text to measure, font is the full CSS font declaration,
// e.g. "bold 12px Verdana"
function measureText(txt, font) {
var id = 'text-width-tester',
$tag = $('#' + id);
if (!$tag.length) {
$tag = $('<span id="' + id + '" style="display:none;font:' + font + ';">' + txt + '</span>');
$('body').append($tag);
} else {
$tag.css({font:font}).html(txt);
}
return {
width: $tag.width(),
height: $tag.height()
}
}
var size = measureText("spam", "bold 12px Verdana");
console.log(size.width + ' x ' + size.height); // 35 x 12.6
为了适应给定的空间,它有点棘手 - 您需要分离出 font-size 声明并适当地缩放它。根据您的工作方式,如果您分解font 声明的不同部分,这可能是最简单的。调整大小函数可能看起来像这样(同样,很明显,这是依赖于 jQuery 的):
function shrinkToFill(input, fontSize, fontWeight, fontFamily) {
var $input = $(input),
txt = $input.val(),
maxWidth = $input.width() + 5, // add some padding
font = fontWeight + " " + fontSize + "px " + fontFamily;
// see how big the text is at the default size
var textWidth = measureText(txt, font).width;
if (textWidth > maxWidth) {
// if it's too big, calculate a new font size
// the extra .9 here makes up for some over-measures
fontSize = fontSize * maxWidth / textWidth * .9;
font = fontWeight + " " + fontSize + "px " + fontFamily;
// and set the style on the input
$input.css({font:font});
} else {
// in case the font size has been set small and
// the text was then deleted
$input.css({font:font});
}
你可以在这里看到这个:http://jsfiddle.net/nrabinowitz/9BFQ8/5/
测试似乎表明这有点令人不安,至少在 Google Chrome 中是这样,因为只使用了全整数字体大小。您可能可以使用基于em 的字体声明做得更好,尽管这可能有点棘手 - 您需要确保文本宽度测试器的1em 大小与输入的大小相同.