调整输入字段的宽度以适应其输入

<input type="text" value="1" style="min-width:1px;" />

This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?

I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.

If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.

451402 次浏览

我认为你误解了最小宽度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();
});
});

听起来好像您希望样式根据文本框的内容动态地应用于文本框的宽度。如果是这样,你将需要一些js来运行文本框内容的变化,比如:

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

注意:此解决方案仅在每个字符的宽度恰好为8px时有效。你可以使用CSS-Unit "ch"(字符),表示字符"0"的宽度;用所选字体。你可以读到它在这里

为了计算当前输入的宽度,你必须将它嵌入到一个临时的span元素中,将它附加到DOM中,使用scrollWidth属性获得计算的宽度(以像素为单位),并再次删除span。当然,你必须确保在input元素和span元素中使用相同的字体系列、字体大小等。因此,我给他们分配了同一个班。

我将函数附加到keyup事件,因为在keypress中输入字符还没有添加到输入value中,所以这将导致错误的宽度。不幸的是,我不知道如何摆脱输入字段的滚动(当添加字符到字段的末尾时);它滚动,因为字符是在adjustWidthOfInput()被调用之前添加和显示的。而且,如前所述,我不能反过来做,因为这样你就会有输入字段之前的值被插入按下的字符。我稍后会设法解决这个问题。

顺便说一句,我只是在Firefox(3.6.8)中测试了这个,但我希望你能明白。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Get/set width of &lt;input&gt;</title>
<style>
body {
background: #666;
}


.input-element {
border: 0;
padding: 2px;
background: #fff;
font: 12pt sans-serif;
}


.tmp-element {
visibility: hidden;
white-space: pre;
}
</style>
</head>
<body>
<input id="theInput" type="text" class="input-element" value="1">
<script>
var inputEl = document.getElementById("theInput");


function getWidthOfInput() {
var tmp = document.createElement("span");
tmp.className = "input-element tmp-element";
tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
document.body.appendChild(tmp);
var theWidth = tmp.getBoundingClientRect().width;
document.body.removeChild(tmp);
return theWidth;
}


function adjustWidthOfInput() {
inputEl.style.width = getWidthOfInput() + "px";
}


adjustWidthOfInput();
inputEl.onkeyup = adjustWidthOfInput;
</script>
</body>
</html>

为了更好的观感

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

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

下面是一个普通的JS,它侦听<input>元素的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>

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

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

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

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

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

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

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

在你的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;

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

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

例如

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

JsFiddle 在这里

以下是对Lyth的回答的修改,考虑到了以下因素:

  • 删除
  • 初始化
  • 占位符

它还允许任意数量的输入字段!要查看它的实际操作:http://jsfiddle.net/4Qsa8/

脚本:

$(document).ready(function () {
var $inputs = $('.resizing-input');


// Resize based on text if text.length > 0
// Otherwise resize based on the placeholder
function resizeForText(text) {
var $this = $(this);
if (!text.trim()) {
text = $this.attr('placeholder').trim();
}
var $span = $this.parent().find('span');
$span.text(text);
var $inputSize = $span.width();
$this.css("width", $inputSize);
}


$inputs.find('input').keypress(function (e) {
if (e.which && e.charCode) {
var c = String.fromCharCode(e.keyCode | e.charCode);
var $this = $(this);
resizeForText.call($this, $this.val() + c);
}
});


// Backspace event only fires for keyup
$inputs.find('input').keyup(function (e) {
if (e.keyCode === 8 || e.keyCode === 46) {
resizeForText.call($(this), $(this).val());
}
});


$inputs.find('input').each(function () {
var $this = $(this);
resizeForText.call($this, $this.val())
});
});

风格:

.resizing-input input, .resizing-input span {
font-size: 12px;
font-family: Sans-serif;
white-space: pre;
padding: 5px;
}

HTML:

<div class="resizing-input">
<input type="text" placeholder="placeholder"/>
<span  style="display:none"></span>
</div>

$(document).ready(function() {
var $inputs = $('.resizing-input');


// Resize based on text if text.length > 0
// Otherwise resize based on the placeholder
function resizeForText(text) {
var $this = $(this);
if (!text.trim()) {
text = $this.attr('placeholder').trim();
}
var $span = $this.parent().find('span');
$span.text(text);
var $inputSize = $span.width();
$this.css("width", $inputSize);
}


$inputs.find('input').keypress(function(e) {
if (e.which && e.charCode) {
var c = String.fromCharCode(e.keyCode | e.charCode);
var $this = $(this);
resizeForText.call($this, $this.val() + c);
}
});


// Backspace event only fires for keyup
$inputs.find('input').keyup(function(e) {
if (e.keyCode === 8 || e.keyCode === 46) {
resizeForText.call($(this), $(this).val());
}
});


$inputs.find('input').each(function() {
var $this = $(this);
resizeForText.call($this, $this.val())
});
});
.resizing-input input,
.resizing-input span {
font-size: 12px;
font-family: Sans-serif;
white-space: pre;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="resizing-input">
First:
<input type="text" placeholder="placeholder" />
<span style="display:none"></span>
</div>
<br>

我真的很喜欢Lyth的回答,但也真的想让它:

  1. 处理退格和删除
  2. 不需要手动添加相邻标签。
  3. 强制最小宽度。
  4. 自动应用于具有特定类的元素

我改编了他的JSFiddle,并提出。这个方法中没有提到的一个改进是使用类似jQuery CSS解析器的方法从输入中实际读取初始宽度。textbox-autosize规则,并使用它作为minWidth。对的,我只是在上面使用一个属性,这使得一个紧凑的演示,但不是理想的。因为每个输入都需要一个额外的属性。你可能还想在JavaScript中把minWidth设置为100。

HTML:

<div id='applicationHost'>
<div>Name:   <input class='textbox-autosize' data-min-width='100' type="text" /></div>
<div>Email:  <input class='textbox-autosize' data-min-width='100' type="email" /></div>
<div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
</div>

CSS:

#applicationHost {
font-family: courier;
white-space: pre;
}


input.textbox-autosize, span.invisible-autosize-helper {
padding:0;
font-size:12px;
font-family:Sans-serif;
white-space:pre;
}
input.textbox-autosize {
width: 100px; /* Initial width of textboxes */
}


/*
In order for the measurements to work out, your input and the invisible
span need to have the same styling.
*/

JavaScript:

$('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
// Add an arbitary buffer of 15 pixels.
var whitespaceBuffer = 15;
var je = $(this);
var minWidth = parseInt(je.attr('data-min-width'));
var newVal = je.val();
var sizingSpanClass = 'invisible-autosize-helper';
var $span = je.siblings('span.' + sizingSpanClass).first();
// If this element hasn't been created yet, we'll create it now.
if ($span.length === 0) {
$span = $('<span/>', {
'class': sizingSpanClass,
'style': 'display: none;'
});
je.parent().append($span);
}
$span = je.siblings('span').first();
$span.text(newVal) ; // the hidden span takes
// the value of the input
$inputSize = $span.width();
$inputSize += whitespaceBuffer;
if($inputSize > minWidth)
je.css("width", $inputSize) ; // apply width of the span to the input
else
je.css("width", minWidth) ; // Ensure we're at the min width
});

这是一个普通的JS和jQuery插件,我写的,将处理调整输入元素使用画布和字体大小/家族,以确定实际的字符串长度时,渲染。(只适用于> IE9, chrome, safari, firefox, opera和大多数其他主要的浏览器,已经实现了画布元素)。

PlainJS:

function autoSize(input, o) {
o || (o = {});
o.on || (o.on = 'keyup');


var canvas = document.createElement('canvas');
canvas.setAttribute('style', 'position: absolute; left: -9999px');
document.body.appendChild(canvas);


var ctx = canvas.getContext('2d');


input.addEventListener(o.on, function () {
ctx.font = getComputedStyle(this,null).getPropertyValue('font');
this.style.width = ctx.measureText(this.value + '  ').width + 'px';
});
}


//Usage
autoSize(document.getElementById('my-input'));

jQuery插件:

$.fn.autoSize = function(o) {
o = $.extend({}, {
on: 'keyup'
}, o);


var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
$('body').append($canvas);


var ctx = $canvas[0].getContext('2d');


return this.on(o.on, function(){
var $this = $(this);
ctx.font = $this.css('font');
$this.width(ctx.measureText($this.val()).width + 'px');
})
}


//Usage:
$('#my-input').autoSize();

注意:这将不处理文本转换,行间距和字母间距,以及其他一些文本大小变化属性。要处理文本转换属性,请设置并调整文本值以匹配该属性。其他的可能相当直截了当。如果这开始获得一些吸引力,我会实施……

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

这里有一个解决方案无等距字体需要,只需要一小段javascript代码不需要计算计算样式,甚至支持输入法支持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.text来适应文本的宽度,并通过position: absolute到容器让输入具有与之相同的大小。每次span改变时,将输入的值复制到span(你可以很容易地将这段代码更改为普通JS,或者使用前端框架提供的特性)。因此,输入将适合其内容的大小。

下面是使用DIV和' contentteditable '属性来解决这个问题的另一种方法:

HTML:

<div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>

CSS:(给DIV一些维度,使它更容易看到)

.fluidInput {


display         : inline-block;
vertical-align  : top;


min-width       : 1em;
height          : 1.5em;


font-family     : Arial, Helvetica, sans-serif;
font-size       : 0.8em;
line-height     : 1.5em;


padding         : 0px 2px 0px 2px;
border          : 1px solid #aaa;
cursor          : text;
}




.fluidInput * {


display         : inline;


}




.fluidInput br  {


display         : none;


}




.fluidInput:empty:before {


content         : attr(data-placeholder);
color           : #ccc;


}

注意:如果你计划在你计划提交的FORM元素中使用这个,你将需要使用Javascript / jQuery来捕获提交事件,这样你就可以解析DIV的“值”(分别为.innerHTML.html())。

基于Michael的回答,我使用jQuery创建了自己的版本。我认为这是大多数答案的一个更简洁的版本,它似乎可以完成工作。

我和这里的大多数人做的是一样的事情,使用span来写入输入文本,然后得到宽度。然后在调用动作keyupblur时设置宽度。

这里是一个工作的codepen。这个代码依赖显示了如何将其用于多个输入字段。

HTML结构:

<input type="text" class="plain-field" placeholder="Full Name">
<span style="display: none;"></span>

jQuery:

function resizeInputs($text) {
var text = $text.val().replace(/\s+/g, ' '),
placeholder = $text.attr('placeholder'),
span = $text.next('span');
span.text(placeholder);
var width = span.width();


if(text !== '') {
span.text(text);
var width = span.width();
}


$text.css('width', width + 5);
};

上面的函数获取输入值,修剪多余的空格,并将文本设置为span以获得宽度。如果没有文本,则获取占位符并将其输入到span中。一旦它将文本输入到span中,它就会设置输入的宽度。宽度上的+ 5是因为没有它,在Edge浏览器中输入会被切断一小部分。

$('.plain-field').each(function() {
var $text = $(this);
resizeInputs($text);
});


$('.plain-field').on('keyup blur', function() {
var $text = $(this);
resizeInputs($text);
});


$('.plain-field').on('blur', function() {
var $text = $(this).val().replace(/\s+/g, ' ');
$(this).val($text);
});

如果这可以改进,请让我知道,因为这是我能想出的最干净的解决方案。

更好的是onvalue:

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

它还包括粘贴、拖放等。

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

因此,通过绑定到input事件,可以将如下简单的东西用作resize函数:

var input = document.querySelector('input'); // get the input element
input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
resizeInput.call(input); // immediately call the function


function resizeInput() {
this.style.width = this.value.length + "ch";
}
input{ font-size:1.3em; padding:.5em; }
<label>Text
<input>
</label>

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

单位ch的一个潜在问题是,在许多字体(如Helvetica)中,字符"m"超过字符0和字符“i”的宽度;更窄。1ch通常比字符的平均宽度宽,根据帖子,通常是20-30%左右。

为什么不使用css呢?

<div id="wrapper">
<input onkeyup="keyup(event)">
<div id="ghost"></div>
</div>

function keyup(e) {
document.getElementById('ghost').innerText = e.target.value;
}
#wrapper {
position: relative;
min-width: 30px;
display: inline-block;
}


input {
position: absolute;
left:0;
right:0;
border:1px solid blue;
width: 100%;
}


#ghost {
color: transparent;
}
<div id="wrapper">
<input onkeyup="keyup(event)">
<div id="ghost"></div>
</div>

wrapper {
position: relative;
min-width: 30px;
border: 1px solid red;
display: inline-block;
}


input {
position: absolute;
left:0;
right:0;
width: 100%;
}


#ghost {
color: transparent;
}

这段代码是由@Iain Todd介绍的,我认为我应该分享它

这是一个特定于angular的答案,但这对我来说很有效,并且在简单性和易用性方面非常令人满意:

<input [style.width.ch]="value.length" [(ngModel)]="value" />

它通过贾尼的回答中的字符单位自动更新。

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

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

注意:根据中数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" />

一个无懈可击的通用方法是:

  1. 考虑被测量的input元素的所有可能的样式
  2. 能够在任何输入上应用测量,而无需修改超文本标记语言

< a href = " https://codepen。io/vsync/pen/ jxong " rel="nofollow noreferrer">代码集演示 . io/vsync/pen/ jxong " rel="nofollow noreferrer">

var getInputValueWidth = (function(){
// https://stackoverflow.com/a/49982135/104380
function copyNodeStyle(sourceNode, targetNode) {
var computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}
  

function createInputMeassureElm( inputelm ){
// create a dummy input element for measurements
var meassureElm = document.createElement('span');
// copy the read input's styles to the dummy input
copyNodeStyle(inputelm, meassureElm);
    

// set hard-coded styles needed for propper meassuring
meassureElm.style.width = 'auto';
meassureElm.style.position = 'absolute';
meassureElm.style.left = '-9999px';
meassureElm.style.top = '-9999px';
meassureElm.style.whiteSpace = 'pre';
    

meassureElm.textContent = inputelm.value || '';
    

// add the meassure element to the body
document.body.appendChild(meassureElm);
    

return meassureElm;
}
  

return function(){
return createInputMeassureElm(this).offsetWidth;
}
})();




// delegated event binding
document.body.addEventListener('input', onInputDelegate)


function onInputDelegate(e){
if( e.target.classList.contains('autoSize') )
e.target.style.width = getInputValueWidth.call(e.target) + 'px';
}
input{
font-size:1.3em;
padding:5px;
margin-bottom: 1em;
}


input.type2{
font-size: 2.5em;
letter-spacing: 4px;
font-style: italic;
}
<input class='autoSize' value="type something">
<br>
<input class='autoSize type2' value="here too">

值得注意的是,当字体为等宽时,可以进行漂亮的调整大小,因此我们可以使用ch单元完美地调整input元素的大小。

同样,在这种方法中,我们可以通过在input事件上更新CSS变量 (自定义属性)来更新字段的宽度,我们还应该注意在DOMContentLoaded事件上已经预先填充的输入

< a href = " https://codepen。io/fcalderan/pen/yEexOZ" rel="noreferrer"> code depen demo . io/fcalderan/pen/yEexOZ" rel="noreferrer">


标记

<input type="text" value="space mono font" class="selfadapt" />

CSS

:root { --size: 0; }


.selfadapt {
padding: 5px;
min-width: 10ch;
font-family: "space mono";
font-size: 1.5rem;
width: calc(var(--size) * 1ch);
}

作为根变量,我们设置了--size: 0:这个变量将包含输入的长度,它将在calc()表达式中乘以1ch。默认情况下,我们也可以设置最小宽度,例如10ch

Javascript部分读取插入值的长度并更新变量--size:

JS

let input = document.querySelector('.selfadapt');
let root  = document.documentElement.style;


/* on input event auto resize the field */
input.addEventListener('input', function() {
root.setProperty('--size', this.value.length );
});


/* resize the field if it is pre-populated */
document.addEventListener("DOMContentLoaded", function() {
root.setProperty('--size', input.value.length);
});

当然,即使你不使用等宽字体,这仍然有效,但在这种情况下,你将需要改变calc()公式,通过将--size变量乘以另一个不同于1ch的值(它严格依赖于font-familyfont-size)。

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

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

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

这是我的2美分。 创建一个空的不可见的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>

很简单:

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

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

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

比较。请仔细注意在第一个字符之后大小的变化。

<p>Subtracting N:</p>
<input type="text" placeholder="enter lots of text here" oninput='this.style.width = (this.scrollWidth-2) + "px";'>


<p>Not Subtracting N:</p>
<input type="text" placeholder="enter lots of text here" oninput='this.style.width = (this.scrollWidth) + "px";'>

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

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

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

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


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


  

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

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

最好的解决方案是<= {input.value大小。长度}/比;

苗条的版本:

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

这是我的反应的解决方案,它适用于任何字体大小,只要确保你有一个单一空间字体(所有字体字符宽度是相同的单一空间字体),就像我的解决方案,它将完美地工作。

JS:

const [value, setValue] = useState(0)

HTML:

<input value={value} onChange={(e) => {setValue(e.target.value)}} style=\{\{width: `${value.toString().length}`ch}}/>

CSS:

@import url("https://fonts.googleapis.com/css2?family=B612+Mono&display=swap");
input{
font-family: "B612 Mono", monospace;
}

更新答案https://stackoverflow.com/a/41389961/1022684

如果你有多个输入并且不想重复输入文本:

  $(() => {
$('.container input').on('input', (e) => {
$(e.target).prev().text($(e.target).val())
})
$('.container input').each((idx, elem) => {
$(elem).prev().text($(elem).val())
})
})