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

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

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

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


当前回答

我真的很喜欢Lyth的回答,但也真的希望它是:

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

我改编了他的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
});

其他回答

在现代浏览器版本中,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%左右。

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

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;
}

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

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

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

I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.

顺便说一句,我只是在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>

演进版:

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