【问题标题】:Auto size text font while typing in textfield在文本字段中键入时自动调整文本字体大小
【发布时间】:2014-05-01 19:26:18
【问题描述】:

我搜索了它,但找不到确切的解决方案。

注意:对于重复制作者,我阅读了这些但无法帮助This & Autosize

我在 html 中有国籍的文本字段,有些国籍是几个字符,如阿联酋、印度等,但有些很长。

如果有人输入了一个冗长的国籍,文本字体应该自动缩小,就像在 PDF 中一样。

这是我的文本字段

<input type="text" size="7" style="float: left; border-width: medium medium 1px; border-style: none none solid; border-color: -moz-use-text-color -moz-use-text-color

 rgb(204, 204, 204); -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none;
 border-image: none; padding: 0px 8px; font: 700 12px verdana;
 text-transform: uppercase; vertical-align: baseline; margin: 0px 5px 0px 0px;" name="client_nationality" value="" id="client_nationality">

Here is js fiddle attached

【问题讨论】:

标签: jquery html css


【解决方案1】:

你可以使用 jquery 类似的东西:

$('.text_font_resize').keyup(function(ev){
if($(this).val().length > 7)
{
    var size =  $(this).css("font-size");
    size = size.slice(0,-2)
    size -= 0.9;
    if(size >= 8)
    {
        $(this).css("font-size",size + "px");
    }
}
if($(this).val().length === 0)
{
    $(this).css("font-size","12px");
}

});

这里是fiddle

可能会有更好的方法.. :)

【讨论】:

  • 这将逐渐使整个文本框越来越小...如果 7 个字符或更少,您需要一个 else 大小写来重置 font-size
  • 越野车,但非常疯狂! :)
  • 是的,应该给 OP 留下一些东西,反正我会做的
  • 这是一个问题,它缩小了文本字段..我不想要那个..怎么做?
  • 那需要检查最小字体大小,你可以增加文本字段长度或者让文本垂直溢出以最小字体大小正常
【解决方案2】:

这可能是 Shrinking font-size at a user types to fit in an input using Javascript 的重复 :)

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

$(function() {
$('#my_input').keyup(function() {
    shrinkToFill(this, 20, "", "Georgia, serif");
 })
});

【讨论】:

    猜你喜欢
    • 2011-02-28
    • 2013-03-28
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    相关资源
    最近更新 更多