<input type="text" value="1" style=" font - family:宋体;/>

这是我的代码,它不工作。在HTML, JavaScript, PHP或CSS中是否有其他方法来设置最小宽度?

我想要一个具有动态变化宽度的文本输入字段,以便输入字段围绕其内容流动。每个输入都有一个2em的内置填充,这就是问题所在,第二个问题是最小宽度在输入上根本不起作用。

如果我设置的宽度超过了需要的宽度,那么整个程序就会很混乱,我需要1px的宽度,只在需要的时候才需要。


当前回答

只是在其他答案的基础上加上。

我注意到现在在一些浏览器的输入字段有一个scrollWidth。这意味着:

this.style.width = this.scrollWidth + 'px';

应该工作得很好。在chrome, firefox和safari测试。

对于删除支持,您可以先添加'=0',然后再重新调整。

this.style.width = 0; this.style.width = this.scrollWidth + 'px';

其他回答

演进版:

<input type="text" style="width: {tag.length}ch" bind:value={tag} />

更好的是onvalue:

<input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">

它还包括粘贴、拖放等。

您希望随着文本的更改而更改size属性。

# react

const resizeInput = (e) => {
  e.target.setAttribute('size', e.target.value.length || 1);
}

<input 
  onChange={resizeInput}
  size={(propertyInput.current && propertyInput.current.value.length) || 1}
  ref={propertyInput} 
/>

  

你可以在angularjs中使用内置的ng风格指令来做得更简单。

在你的html中:

  <input ng-style="inputStyle(testdata)" ng-model="testdata" />

在你的控制器中:

 $scope.testdata = "whatever";

 $scope.inputStyle = function(str) {
    var charWidth = 7;
    return  {"width": (str.length +1) * charWidth + "px" };
    };

在你的css中:

input { font-family:monospace; font-size:12px; }

调整charWidth以匹配字体的宽度。它看起来是7,字体大小为12px;

您还可以使用size属性设置输入的宽度。输入的大小决定了它的字符宽度。

输入可以通过监听关键事件动态地调整它的大小。

例如

$("input[type='text']").bind('keyup', function () {
    $(this).attr("size", $(this).val().length );
});

关于这个课题JsFiddle