jQuery - auto size text input (not textarea!) [dup

2019-01-03 05:47发布

This question already has an answer here:

How do I auto-resize the input type="text" field with jQuery? I want it to be like 100px wide at the start, then make it auto-widening as user inputs text... is that possible?

9条回答
Summer. ? 凉城
2楼-- · 2019-01-03 06:40

I don't think there is a perfect solution to that problem because you cannot detect the actual width of the text entered to the input element. It all depends of the font you are using, zoom settings in browser etc.

However if you can choose a font where you can actually calculate the number of pixels that text have (this is the hardest part but I guess you can try to estimate it somehow). You can use this to change the width of your input field.

 $('input').keyup(function () {
     // I'm assuming that 1 letter will expand the input by 10 pixels
     var oneLetterWidth = 10;

     // I'm also assuming that input will resize when at least five characters
     // are typed
     var minCharacters = 5;
     var len = $(this).val().length;
     if (len > minCharacters) {
         // increase width
         $(this).width(len * oneLetterWidth);
     } else {
         // restore minimal width;
         $(this).width(50);
     }
 });
查看更多
3楼-- · 2019-01-03 06:40

By default, input width is controlled by the size parameter, which for type="text" corresponds to number of characters wide it should be.

Since this is measured in characters and not pixels, the actual pixel size is controlled by the (fixed-width) font in use.

查看更多
小情绪 Triste *
4楼-- · 2019-01-03 06:40

I was just thinking about the same thing. Textbox should resize it self as user is writing text into it. I never used it, but I have an idea how to do it. Something like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  </head>
  <body>

  <table border="1">
  <tr>
    <td>
      <span id="mySpan">
        <span id="mySpan2"></span>
        <input id="myText" type="text" style="width:100%" onkeyup="var span = document.getElementById('mySpan2');var txt = document.getElementById('myText'); span.innerHTML=txt.value;">
       </span>
    </td>
    <td>
            sss
    </td>
  </tr>
</table>

  </body>
</html>
查看更多
登录 后发表回答