【问题标题】:Make HTML input font size shrink as more type is typed输入更多类型时使 HTML 输入字体大小缩小
【发布时间】:2019-05-12 12:20:08
【问题描述】:

我有一个 3 个字符的 HTML 文本字段。如果用户输入 4 个字符,我希望缩小字体大小以适应这四个字符。

Acrobat 对表单有这种行为。我想要 HTML 中的这种行为。

也就是说,如果我有一个包含 3 个字符的文本字段:

而用户键入一个 4,我希望文字缩小:

【问题讨论】:

  • 你只能用JS来做,html/css中有这样的功能

标签: html css text responsive-design


【解决方案1】:

这在 HTML/CSS 中是不可能的——这个解决方案使用 JS+JQuery

找到这个:https://github.com/vxsx/jquery.inputfit.js 演示:http://vxsx.github.io/jquery.inputfit.js/

<input type="text" name="younameit" id="input">
<script type="text/javascript">
    $('#input').inputfit();
</script>

【讨论】:

  • 非常简单的解决方案!谢谢。
【解决方案2】:

我认为你想要的可以用一些非常简单的 javascript 方法来完成。但是,不幸的是,在 html 或 css 中没有这样做的方法。下一个代码是我发现的,由 u/adactio 编写。在 github 上。

<script>
  window.fitText( document.getElementById("responsive_headline") );
</script>

window.fitText( document.getElementById("responsive_headline"), 1.2 );
 // turn the compressor up (font will shrink a bit more aggressively)
window.fitText( document.getElementById("responsive_headline"), 0.8 ); 
// turn the compressor down (font will shrink less aggressively)

确保编辑掉“responsive_headline”! 干杯!

【讨论】:

    【解决方案3】:

    您需要使用 javascript。 这通过检查输入是否可以滚动来工作,如果可以,则表示内容已溢出,在这种情况下,字体大小应该变小。
    希望这会有所帮助!

    function changefontsize() {
      var myInput = document.getElementById('myInput');
      if(isOverflown(myInput)) {
        while (isOverflown(myInput)){
        currentfontsize--;
        myInput.style.fontSize = currentfontsize + 'px';
        }
      }else {
        currentfontsize = 13;
        myInput.style.fontSize = currentfontsize + 'px';
        while (isOverflown(myInput)){
        currentfontsize--;
        myInput.style.fontSize = currentfontsize + 'px';
        }
      }	
    }
    
    function isOverflown(element) {
        return element.scrollWidth > element.clientWidth;
    }
    #myInput {
      padding:5px;
      border-radius:3px;
      font-family:Arial;
      width:100px;
      font-size:13px;
      height:20px;
    }
    Type Here -&gt; &lt;input type="text" id="myInput" onkeypress="changefontsize()" onchange="changefontsize()"&gt;

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 2021-11-07
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 2021-12-19
      • 2017-02-25
      相关资源
      最近更新 更多