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

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

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

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


当前回答

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

其他回答

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

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

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

注意:这个解决方案只适用于每个字符都是8px宽的情况。您可以使用CSS-Unit“ch”(字符),它表示所选字体中字符“0”的宽度。你可以在这里阅读。

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

考虑所有可能的测量输入元素的样式 能够在任何输入上应用测量,而无需修改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">

以下是对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的回答,但也真的希望它是:

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

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