elastic textfield
<form action="" method="">
<input name="title" type="text" maxlength="256" value="daniel"/>
<input name="description" type="text" maxlength="512" value="awesome"/>
</form>
JavaScript:
function resize(elem){
if(!elem.value.length) elem.size=1;
el开发者_高级运维se elem.size=elem.value.length;
}
var elem=document.getElementsByTagName('input');
for(i in elem){
elem[i].addEventListener('keyup', function(){resize(this);}, false);
resize(elem[i]);
}
CSS:
input{
display:block;
font-size:12px;
}
all of this is working, but i am not quite satisfied. as you can see actual text representation is quite smaller than text field boundaries. this is pronounced as text gets longer. is there any css trick to minimize this offset?
you can check example page HERE
many thanks!
If you use a proportional font, the size of the field is always only going to be approximately correct when given in fixed units like the size
attribute (or CSS's em
units). You could mitigate this by making the font of the input
monospaced, but that's obviously got some downsides.
The only solution I'm aware of for doing this to a high level of quality involves an off-screen element (a span
is good) that's allowed to grow automatically, and then mapping the size of that div onto the size of the element.
Update: Here's an example: http://jsfiddle.net/zUBar/5/ Apologies, I don't do computed widths manually, so I've added jQuery into the mix for the purposes of the example. If you don't use jQuery, you should be able to use the features of the library you do use (or getComputedStyle
or similar) to get the same information, which is the resulting width of the off-screen span. Things of note:
- You need to give the browser a moment to resize the
span
, hence thesetTimeout
- The
span
is off to the far left of the page, which prevents scrollbars from appearing unnecessarily - I've explicitly set the same font for the
input
and thespan
Example solution: http://jsfiddle.net/7Ubch/
The size
attribute is unfortunately rather imprecise; it makes more sense to set the width of the element via the style
property.
Here's an example of a method that uses a hidden pre
element with the same font as the input element to provide a more accurate width. I've used the keydown
event as well as keyup
because the former fires on each key repeat. Using a pre
element means that multiple space characters are not collapsed.
(Of course, I dove straight into the code, but I just thought to search and someone wrote a simple jQuery plugin that does the same job as this. I've stuck to plain old DOM methods, but it might be useful if you go down that route in the future.)
精彩评论