使用 Javascript 缩小用户键入时的字体大小以适合输入

发布于 2024-11-09 14:50:48 字数 276 浏览 0 评论 0原文

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

虽然我可以看到如何在每次按键时执行一个功能,但我很好奇如何每次都计算字体大小,以便它始终适合输入字段。有没有办法测量可变宽度字体的一段文本的长度?他们是如何达到这样的效果的呢?

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

Apple's MobileMe uses Javascript to change the font size in the email login on its homepage as the user types so that the text always fits in the available space without overflow scrolling.

While I can see how how to execute a function on each keypress, I'm curious how one would go about calculating the font-size each time so that it always fits into the input field. Is there a way to measure the length of a piece of text with a variable width font? How do they accomplish this effect?

Try it out to see what I mean:
http://www.me.com/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

软糯酥胸 2024-11-16 14:50:48

我过去曾使用 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 大小宽度测试器与输入的宽度测试器相同。

I've done this in the past using jQuery. You can measure the size of a piece of text like this:

// 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

In order to fit this to a given space, it's a little trickier - you need to separate out the font-size declaration and scale it appropriately. Depending on how you're doing things, this might be easiest if you break out the different parts of the font declaration. A resize function might look like this (again, obviously, this is jQuery-dependent):

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});
}

You can see this in action here: http://jsfiddle.net/nrabinowitz/9BFQ8/5/

Testing seems to show that this is a little jumpy, at least in Google Chrome, because only full-integer font sizes are used. You might be able to do better with a em-based font declaration, though this might be a little tricky - you'd need to ensure that the 1em size for the text width tester is the same as that for the input.

夏九 2024-11-16 14:50:48

我从其他答案的大杂烩中又做了一个。我认为这提供了最简单的单一属性更改解决方案。

它可能过于冗长,或者可以在某些方面进行重构以使其清晰,欢迎任何建议!

$(document).ready(function(){

    // get the current styles size, in px integer.
    var maxSize = parseInt($('.fields').css("font-size"));

    function isOverflowed (element){

        if ( $(element)[0].scrollWidth > $(element).innerWidth() ) {
            return true;
        } else {
            return false;
        }
    };

    function decreaseSize (element){

        var fontSize = parseInt($(element).css("font-size"));
        fontSize = fontSize - 1 + "px";
        $(element).css({'font-size':fontSize});

    }

    function maximizeSize (element){

        var fontSize = parseInt($(element).css("font-size"));
        while (!isOverflowed(element) && fontSize < maxSize){
            fontSize = fontSize + 1 + "px";
            $(element).css({'font-size':fontSize});

            // if this loop increases beyond the width, decrease again. 
            // hacky.
            if (isOverflowed(element)){
                while (isOverflowed(element)) {
                    decreaseSize(element);
                }            
            }     

        }        

    }

    function fixSize (element){
        if (isOverflowed(element)){
            while (isOverflowed(element)) {
                decreaseSize(element);
            }            
        } else {
            maximizeSize(element);
        }
    }

    // execute it onready.
    $('.fields').each(function(){
        fixSize(this);
    });

    // bind to it.
    $(function() {
        $('.fields').keyup(function() {
            fixSize(this);
        })
    });    

});

I made another one from a hodgepodge of other answers. I think this provides the simplest one-property-change solution.

It's likely overly verbose or could be refactored for clarity in some ways, any suggestions welcomed!

$(document).ready(function(){

    // get the current styles size, in px integer.
    var maxSize = parseInt($('.fields').css("font-size"));

    function isOverflowed (element){

        if ( $(element)[0].scrollWidth > $(element).innerWidth() ) {
            return true;
        } else {
            return false;
        }
    };

    function decreaseSize (element){

        var fontSize = parseInt($(element).css("font-size"));
        fontSize = fontSize - 1 + "px";
        $(element).css({'font-size':fontSize});

    }

    function maximizeSize (element){

        var fontSize = parseInt($(element).css("font-size"));
        while (!isOverflowed(element) && fontSize < maxSize){
            fontSize = fontSize + 1 + "px";
            $(element).css({'font-size':fontSize});

            // if this loop increases beyond the width, decrease again. 
            // hacky.
            if (isOverflowed(element)){
                while (isOverflowed(element)) {
                    decreaseSize(element);
                }            
            }     

        }        

    }

    function fixSize (element){
        if (isOverflowed(element)){
            while (isOverflowed(element)) {
                decreaseSize(element);
            }            
        } else {
            maximizeSize(element);
        }
    }

    // execute it onready.
    $('.fields').each(function(){
        fixSize(this);
    });

    // bind to it.
    $(function() {
        $('.fields').keyup(function() {
            fixSize(this);
        })
    });    

});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文