尺寸改变<input />

时间:2016-03-03 16:53:13

标签: javascript html css width textfield

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

修改
它只是简单的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>

2 个答案:

答案 0 :(得分:1)

这应该足够好了:

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

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

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

答案 1 :(得分:0)

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

&#13;
&#13;
$(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');
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题