将input字段的宽度调整为其input

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

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

Marcel澄清: OP需要一个宽度dynamic变化的文本input字段,以使input字段在其内容周围stream动。

这听起来像你期望的是,风格是dynamic应用的基于文本框的内容的文本框的宽度。 如果是这样,你将需要一些js运行文本框内容更改,如下所示 :

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

注意:此解决scheme只适用于每个字符正好8px宽。

要计算当前input的宽度,您必须将其embedded临时span元素中,将其附加到DOM,使用scrollWidth属性获取计算的宽度(以像素为单位), scrollWidth再次删除span 。 当然,您必须确保在inputspan元素中使用相同的字体系列,字体大小等。 所以我给他们分配了同一个class级。

我将函数附加到keyup事件,因为在keypress上input字符还没有添加到inputvalue ,所以会导致错误的宽度。 不幸的是,我不知道如何摆脱input字段的滚动(当字符添加到字段的末尾); 它会滚动,因为在调用adjustWidthOfInput()之前添加并显示字符。 而且,正如所说的,我不能这样做,因为插入按下的字符之前 ,您将具有input字段的值。 我会尽量在稍后解决这个问题。

顺便说一下,我只在Firefox(3.6.8)中testing过,但是你会明白的。

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

这是对Lyth的回答的修改,考虑到:

  • 删除
  • 初始化
  • 占位符

它也允许任何数量的input字段! 要看到它的行动: 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> 

为更加新娘看和感觉

您应该使用jQuery keypress()事件与String.fromCharCode(e.which)组合来获取按下的字符。 因此,你可以计算你的宽度将是什么。 为什么? 因为它会看起来更性感:)

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

基本的HTML。

 <input type="text" /> <span style="display:none"></span> 

jQuery。

 $('input[type="text"]').keypress(function(e) { if (e.which !== 0 && e.charCode !== 0) { // only characters var c = String.fromCharCode(e.keyCode|e.charCode); $span = $(this).siblings('span').first(); $span.text($(this).val() + c) ; // the hidden span takes // the value of the input $inputSize = $span.width() ; $(this).css("width", $inputSize) ; // apply width of the span to the input } }) ; 

css。

 input, span { padding:0; font-size:9px; font-family:Sans-serif; white-space:pre; // white-spaces will work effectively } /* it's important the input and its span have same styling */ 

你可以做这样的事情

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

您也可以使用size属性来设置input的宽度。 input的大小决定了字符的宽度。

input可以通过监听关键事件来dynamic调整它的大小。

例如

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

JsFiddle 在这里

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

因此,像下面这样简单的东西可以用作resize的函数:

    函数resizeInput(elem)
     {
        elem.style.width = elem.value.length + 2 +“ch”;
     }

这个例子会将“elem”的值调整为+ 2个字符的值。

这是一个不需要等宽字体的解决scheme, 需要很小的JavaScript代码, 不需要计算计算样式 ,甚至支持ime

 // 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="jquery-3.2.0.min.js"></script> <div class="container"> <span class="text"> some text </span> <input class="input" value="some text" /> </div> 

这里是一个普通的JS和我写的jQuery插件,它将处理使用canvas和字体大小/系列来确定实际string长度时调整input元素的大小。 (只适用于IE9,Chrome,safari,firefox,opera和其他大多数实现了canvas元素的主stream浏览器)。

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

注意:这不会处理文本转换,行间距和字母间距,以及可能的其他文本大小更改属性。 处理文本转换属性集并调整文本值以匹配该属性。 其他人可能相当简单。 如果这开始获得一些牵引力,我会执行…

使用内置的ng样式指令,您可以在angularjs中执行更简单的操作。

在你的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的字体大小;

我认为你误解了最小宽度的CSS属性 。 最小宽度通常用于在stream体布局中定义最小DOM宽度,如下所示:

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

这将设置input元素的最小宽度为200像素。 在这种情况下,“px”代表“像素”。

现在,如果您正在尝试检查以确保input字段在用户提交时至less包含一个字符 ,则需要使用JavaScript和PHP进行一些表单validation。 如果这确实是你想要做的,我会编辑这个答案,并尽我所能帮助你。

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

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

我改编了他的JSFiddle,想出了这个 。 在这个小提琴中没有提到的一个改进就是使用类似jQuery CSS Parser的东西来实际读取input.textbox-autosize规则的初始宽度,并将其用作minWidth。 对,我只是使用一个属性,这使得一个简洁的演示,但不是理想的。 因为每个input都需要额外的属性。 你也可能只想把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 }); 

对不起,join这么晚的这个派对。

我只是想说明一个简单的宽度计算方法 – 假设你不介意使用monospace字体系列来deviseinput字段。

Tahbaza的解决scheme将与monospace字体家族合作。

即使“无形范围”解决scheme无疑是最精确的解决scheme,即使在等空间,我认为这是一个矫枉过正。

这是一个很好的angularjs指令来实现它。

请注意,你应该总是添加“1”字符的实际值 – 否则你会感到烦人的滴答声。

这是代码:

 app.directive("editInline", function(){ return function(scope, element, attr){ var inputW = (element.val().length+1) * 8; element.css('width', inputW + 'px'); element.bind("keyup keydown", function(){ var inputW = (element.val().length+1) * 8; element.css('width', inputW + 'px'); }); } }); <input type="text" style="font-family:monospace" value="hello world" edit-inline> 

以下是使用DIV和“contenteditable”属性解决此问题的另一种方法:

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来捕获提交事件,以便您可以parsing“值”( .innerHTML.html()分别)的DIV。

更好的是:

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

它也涉及粘贴,拖放等。

我只是花了一些时间搞清楚如何做到这一点。
其实我find的最简单的方法是将input值移动到input前的范围,保持input1符号宽度。 虽然我不能确定它是否适合您的初始需求。
也许它是一些额外的代码,但在基于反应+通量的应用程序中,这是非常自然的解

基于迈克尔的回答,我用jQuery创build了自己的版本。 我认为这是大多数答案的一个更简洁的版本,而且似乎完成了这项工作。

我和大多数人一样,用span来写input文本,然后得到宽度。 然后我设置的宽度,当行动keyupblur被调用。

这是一个工作的codepen 。 这codepen显示如何可以用于多个input字段。

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

上面的函数获取input值,修剪多余的空格,并将文本设置为跨度来获取宽度。 如果没有文本,它会取而代之的是占位符并将其input到跨度中。 一旦它进入跨度的文本,然后设置input的宽度。 宽度上的+ 5是因为没有这个input在边缘浏览器中被切断一点点。

 $('.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); }); 

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