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

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

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

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


当前回答

如果你使用Bootstrap,它可以很容易地完成:

<div contenteditable="true" class="form-control" style="display: inline"></div>

您只需要获取div的内容,并在提交表单之前将其放入隐藏输入中。

其他回答

我认为你误解了最小宽度CSS属性。min-width通常用于在流体布局中定义最小DOM宽度,例如:

input {
  width: 30%;
  min-width: 200px;
}

这将把输入元素的最小宽度设置为200像素。在这里,“px”代表“像素”。

现在,如果您试图在用户提交输入字段时确保输入字段至少包含一个字符,则需要使用JavaScript和PHP进行一些表单验证。如果这确实是你想要做的,我会编辑这个答案,尽我最大的努力帮助你。

你可以这样做

// HTML
<input id="input" type="text" style="width:3px" />
// jQuery
$(function(){
  $('#input').keyup(function(){
    $('<span id="width">').append( $(this).val() ).appendTo('body');
    $(this).width( $('#width').width() + 2 );
    $('#width').remove();
  });
});

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

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

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

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

很简单:

oninput='this.style.width = (this.scrollWidth - N) + "px";'

其中N是某个数字(例子中的2,我正在开发的东西上的17),这是由实验确定的。

减去N可以防止这个奇怪的多余空间在文本到达文本框的末尾之前很久就开始积累。

比较。请仔细注意在第一个字符之后大小是如何变化的。 < p >减去N: < / p > <input type="text" placeholder="enter lots of text here" oninput='this.style. "'> . width = (this.scrollWidth-2) + "px" <p>Not minus N:</p> <input type="text" placeholder="enter lots of text here" oninput='this.style. "width = (this.scrollWidth) + "px"

这个答案提供了在浏览器中检索文本宽度的最准确的方法之一,比公认的答案更准确。它使用canvas html5元素,不像其他答案,不将元素添加到DOM,从而避免了过多添加元素到DOM引起的任何回流问题。

阅读更多关于Canvas元素与文本宽度的关系。

注意:根据MDN, getPropertyValue()方法的简写版本(如font)可能不可靠。我建议单独获取值以提高兼容性。我只是为了提高速度才用的。

/** * returns the width of child text of any DOM node as a float */ function getTextWidth(el) { // uses a cached canvas if available var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas")); var context = canvas.getContext("2d"); // get the full font style property var font = window.getComputedStyle(el, null).getPropertyValue('font'); var text = el.value; // set the font attr for the canvas text context.font = font; var textMeasurement = context.measureText(text); return textMeasurement.width; } var input = document.getElementById('myInput'); // listen for any input on the input field input.addEventListener('input', function(e) { var width = Math.floor(getTextWidth(e.target)); // add 10 px to pad the input. var widthInPx = (width + 10) + "px"; e.target.style.width = widthInPx; }, false); #myInput { font: normal normal 400 normal 18px / normal Roboto, sans-serif; min-width: 40px; } <input id="myInput" />