我试图创建读取文本框中的所有字符并返回字体大小值的方法。基于jquery中的字符计算字体大小
我的功能不正常。以下是我的代码
function sizeInput(input) {
return shrinkToFill(input, 48, '', 'Impact');
}
function shrinkToFill(input, fontSize, fontWeight, fontFamily) {
var font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
var $input = $(input);
var maxWidth = $input.width() - 50;
// we're only concerned with the largest line of text.
var longestLine = $input.val().split('\n').sort(function (a, b) {
return measureText(a, font).width - measureText(b, font).width;
}).pop();
var textWidth = measureText(longestLine, 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 * 0.9;
font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
// and set the style on the input
}
else {
font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
// and set the style on the input
}
$input.css({
'font-size': fontSize
});
return fontSize;
}
var measureText = function (str, font) {
str = str.replace(/ /g, ' ');
var id = 'text-width-tester';
var $tag = $('#' + id);
if (!$tag.length) {
$tag = $('<span id="' + id + '" style="display:none;font:' + font + ';">' + str + '</span>');
$('body').append($tag);
} else {
$tag.css({
font: font
}).html(str);
}
return {
width: $tag.width(),
height: $tag.height()
};
};
var topText = $('#topText');
var bottomText = $('#bottomText');
var textUpdated = function() {
var topFontSize = sizeInput(topText);
var bottomFontSize = sizeInput(bottomText);
};
它不会返回任何错误,但它不起作用。
岂不是更容易阅读适用的CSS? – Difster
检查我更新的代码,我只想简单的方法返回基于chanrecter的字体大小。 –
你可以把它放在jsFiddle然后添加链接,? – Difster