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

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

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

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


当前回答

您希望随着文本的更改而更改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} 
/>

  

其他回答

在现代浏览器版本中,CSS单元ch也是可用的。根据我的理解,它是一个与字体无关的单位,其中1ch等于任何给定字体中字符0(零)的宽度。

因此,通过绑定到输入事件,像下面这样简单的东西可以用作resize函数:

var input = document.querySelector('input');//获取输入元素 输入。addEventListener(“输入”,resizeInput);//在"input"事件上绑定"resizeInput"回调 resizeInput.call(输入);//立即调用函数 函数resizeInput() { This.style.width = this.value.length + "ch"; } 输入{字体大小:1.3 em;填充:.5em;} < >标签文本 <输入> < / >标签

该示例将输入大小调整为值的长度+ 2个字符。

单位ch的一个潜在问题是,在许多字体(如Helvetica)中,字符“m”的宽度超过字符0的宽度,而字符“i”要窄得多。1ch通常比字符平均宽度宽,根据这篇文章,通常是20-30%左右。

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

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

例如

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

关于这个课题JsFiddle

你可以设置大小属性。 如果你正在使用一个响应式框架,下面的代码就足够了:

<input size="{{ yourValue.length }}" [value]="yourValue" />

但如果你使用纯js,你应该设置事件处理程序,像这样:

<input oninput="this.setAttribute('size', this.value.length)" />

为了更好的外观和感觉

你应该使用jQuery keypress()事件结合String.fromCharCode(e.which)来获得按下的字符。因此你可以计算你的宽度。为什么?因为这样看起来会更性感:)

下面是一个jsfiddle,与使用keyup事件的解决方案相比,它产生了良好的行为:http://jsfiddle.net/G4FKW/3/

下面是一个普通的JS,它监听<input>元素的输入事件,并将span兄弟元素设置为具有相同的文本值,以便测量它。

document.querySelector('input').addEventListener('input', onInput) function onInput(){ var spanElm = this.nextElementSibling; spanElm.textContent = this.value; // the hidden span takes the value of the input; this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input }; /* it's important the input and its span have same styling */ input, .measure { padding: 5px; font-size: 2.3rem; font-family: Sans-serif; white-space: pre; /* white-spaces will work effectively */ } .measure{ position: absolute; left: -9999px; top: -9999px; } <input type="text" /> <span class='measure'></span>

这是我的两分钱。 创建一个空的不可见的div。用输入内容填充它,并返回输入字段的宽度。匹配每个框之间的文本样式。

$(".answers_number").keyup(function(){ $( "#number_box" ).html( $( this ).val() ); $( this ).animate({ width: $( "#number_box" ).width()+20 }, 300, function() { }); }); #number_box { position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; padding:0 4px; /*Your font styles to match input*/ font-family:Arial; font-size: 30px; } .answers_number { font-size: 30px; font-family:Arial; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" class="answers_number" /> <div id="number_box"> </div>