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

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

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

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


当前回答

这是我的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;
}

其他回答

要计算当前输入的宽度,您必须将其嵌入到一个临时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>

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

考虑所有可能的测量输入元素的样式 能够在任何输入上应用测量,而无需修改HTML或

Codepen演示

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">

这个答案提供了在浏览器中检索文本宽度的最准确的方法之一,比公认的答案更准确。它使用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" />

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

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

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