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

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

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

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


当前回答

很简单:

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"

其他回答

我只是花了些时间来弄清楚怎么做。 实际上,我发现的最简单的方法是将输入值移动到span之前的输入,保持输入1个符号宽度。虽然我不确定它是否适合你最初的需求。 也许它需要一些额外的代码,但在react+flux的应用程序中,这是非常自然的解决方案。

下面是一个简单的函数来获取所需的内容:

function resizeInput() {
    const input = document.getElementById('myInput');
    input.style.width = `${input.scrollWidth}px`;
};

很简单:

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"

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

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

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

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

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

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

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

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

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