大小改变 <input>

Size-changing <input>

我的 HTML 中有一个文本字段,在聚焦时底部边框为白色,我希望它将文本字段的宽度更改为其中当前文本的长度(当然有一些限制)。我尝试了 css min-width 和 max-width,但似乎什么也没做。我认为用 JS 实现它需要硬编码宽度 table,我不想这样做。

编辑:
很简单CSS,但是代码如下:

#container {
  width: 100%;
  height: 52px;
  background: #673ab7;
}

#textbox {
  font-family: sans-serif;
  font-size: 20px;
  font-weight: bold;
  color: white;
  background: none;
  border: none;
  vertical-align: top;
  margin-top: 13px;
  margin-left: 13px;
  outline: none;
}

#textbox:focus {
  border-bottom: 2px solid white;
}
<div id="container">
  <input type="text" id="textbox" placeholder="placeholder" />
</div>

这应该工作得很好:

<form>
<input type="text" id="textfield" onkeyup="changeSize()">
</form>

var sizeIs=20;
function changeSize(){
sizeIs=sizeIs+5;
document.getElementById("textfield").style.width= sizeIs+"px";
}

它的作用是,每次用户键入一个字符时,该函数都会触发并增加文本字段的大小。您可以以此为指导来做任何您需要做的事情。

在我找到 this 之后,我找到了一种无需任何宽度硬编码的方法。 我在这里使用 jQuery 是因为我已经在我的项目中使用过它,但是将它移植到纯 JavaScript 应该相对容易。 &<> 和 space 等字符可能会导致错误,因此需要将其替换为 &...; 编码。

$(document).ready(function(){
  $('#textbox').on('input', function(){
    if($('#textbox').val().length == 0){
      $('#measure').html($('#textbox').attr('placeholder'));
    }else{
      var text = $('#textbox').val();
      text = text.replace(/&/g, '&amp;');
      text = text.replace(/</g, '&lt;');
      text = text.replace(/>/g, '&gt;');
      text = text.replace(/ /g, '&nbsp;');
      $('#measure').html(text);
    }
    
    var w = $('#measure').width();
    if(w > 600) w = 600;
    $('#textbox').width(w);
  });
  
  $('#textbox').trigger('input');
});
html, body {
  margin: 0;
}

#container {
  width: 100%;
  height: 52px;
  background: #673ab7;
}

#textbox {
  font-family: sans-serif;
  font-size: 20px;
  font-weight: bold;
  color: white;
  background: none;
  border: none;
  vertical-align: top;
  margin-top: 13px;
  margin-left: 13px;
  outline: none;
}

#textbox:focus {
  border-bottom: 2px solid white;
}

#measure {
  position: absolute;
  visibility: hidden;
  height: auto;
  width: auto;
  white-space: nowrap;
  font-size: 20px;
  font-weight: bold;
  font-family: sans-serif;
  padding: 0;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <input type="text" id="textbox" placeholder="placeholder" />
</div>

<div id="measure"></div>