<input type="text" value="1" style=" font - family:宋体;/>
这是我的代码,它不工作。在HTML, JavaScript, PHP或CSS中是否有其他方法来设置最小宽度?
我想要一个具有动态变化宽度的文本输入字段,以便输入字段围绕其内容流动。每个输入都有一个2em的内置填充,这就是问题所在,第二个问题是最小宽度在输入上根本不起作用。
如果我设置的宽度超过了需要的宽度,那么整个程序就会很混乱,我需要1px的宽度,只在需要的时候才需要。
<input type="text" value="1" style=" font - family:宋体;/>
这是我的代码,它不工作。在HTML, JavaScript, PHP或CSS中是否有其他方法来设置最小宽度?
我想要一个具有动态变化宽度的文本输入字段,以便输入字段围绕其内容流动。每个输入都有一个2em的内置填充,这就是问题所在,第二个问题是最小宽度在输入上根本不起作用。
如果我设置的宽度超过了需要的宽度,那么整个程序就会很混乱,我需要1px的宽度,只在需要的时候才需要。
当前回答
最好的解决方案是<input…= {input.value大小。长度}/ >
其他回答
我认为你误解了最小宽度CSS属性。min-width通常用于在流体布局中定义最小DOM宽度,例如:
input {
width: 30%;
min-width: 200px;
}
这将把输入元素的最小宽度设置为200像素。在这里,“px”代表“像素”。
现在,如果您试图在用户提交输入字段时确保输入字段至少包含一个字符,则需要使用JavaScript和PHP进行一些表单验证。如果这确实是你想要做的,我会编辑这个答案,尽我最大的努力帮助你。
为了更好的外观和感觉
你应该使用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>
下面是一个简单的函数来获取所需的内容:
function resizeInput() {
const input = document.getElementById('myInput');
input.style.width = `${input.scrollWidth}px`;
};
只是在其他答案的基础上加上。
我注意到现在在一些浏览器的输入字段有一个scrollWidth。这意味着:
this.style.width = this.scrollWidth + 'px';
应该工作得很好。在chrome, firefox和safari测试。
对于删除支持,您可以先添加'=0',然后再重新调整。
this.style.width = 0; this.style.width = this.scrollWidth + 'px';
这是一个不需要等宽字体的解决方案,只需要非常小的javascript代码,不需要计算计算样式,甚至支持IME,支持RTL文本。
// copy the text from input to the span $(function () { $('.input').on('input', function () { $('.text').text($('.input').val()); }); }); * { box-sizing: border-box; } .container { display: inline-block; position: relative; } .input, .text { margin: 0; padding: 2px 10px; font-size: 24px; line-height: 32px; border: 1px solid #ccc; box-radius: 3px; height: 36px; font: 20px/20px sans-serif; /* font: they should use same font; */ } .text { padding-right: 20px; display: inline-block; visibility: hidden; white-space: pre; } .input { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; } <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script> <div class="container"> <span class="text"> some text </span> <input class="input" value="some text" /> </div>
利用张成的空间。文本来适应文本的宽度,并让输入有相同的大小与它的位置:绝对容器。每次变化时,将输入的值复制到span中(您可以轻松地将这段代码更改为普通JS,或者使用前端框架提供的特性)。因此,输入将适合其内容的大小。