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

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

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

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


当前回答

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

其他回答

以下是对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>

这是一个不需要等宽字体的解决方案,只需要非常小的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,或者使用前端框架提供的特性)。因此,输入将适合其内容的大小。

我认为你误解了最小宽度CSS属性。min-width通常用于在流体布局中定义最小DOM宽度,例如:

input {
  width: 30%;
  min-width: 200px;
}

这将把输入元素的最小宽度设置为200像素。在这里,“px”代表“像素”。

现在,如果您试图在用户提交输入字段时确保输入字段至少包含一个字符,则需要使用JavaScript和PHP进行一些表单验证。如果这确实是你想要做的,我会编辑这个答案,尽我最大的努力帮助你。

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

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

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

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

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

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