缩小用户类型的字体大小以使用Javascript适合输入

And*_*ade 9 javascript user-input input javascript-events font-size

Apple的MobileMe使用javascript在用户输入时更改其主页上电子邮件登录中的字体大小,以便文本始终适合可用空间而不会溢出滚动.

虽然我可以看到如何在每个按键上执行一个函数,但我很好奇每次如何调整字体大小以便它总是适合输入字段.有没有办法用可变宽度字体来测量一段文本的长度?他们如何实现这种效果?

试试看我的意思:http: //www.me.com/

nra*_*itz 27

我以前使用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
Run Code Online (Sandbox Code Playgroud)

为了使它适合给定的空间,这有点棘手 - 你需要将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});
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到这个:http://jsfiddle.net/nrabinowitz/9BFQ8/5/

测试似乎表明这有点跳跃,至少在谷歌浏览器中,因为只使用全整数字体大小.您可以使用em基于字体的声明做得更好,尽管这可能有点棘手 - 您需要确保1em文本宽度测试器的大小与输入的大小相同.