My plug-in implements adaptive width in the の input text box.
First come to the final result: DEMO
This section describes how to make the width of a text box increase with the width of the content in the text box, that is, to achieve the adaptive effect of width.
The code example is as follows:
<!DOCTYPE html>
<script type="text/javascript">
window.onload=function(){
var otxt=document.getElementById("txt");
otxt.onkeyup=function(){
this.size=(this.value.length>4?this.value.length:4);
}
}
</script>
<body>
<input type="text" id="txt" size="4"/>
</body>
View Demonstration: Adaptive width of input text box
The above Code meets our requirements. The code is very simple. register the onkeyup event handler function. This function can determine whether the length of the input content is greater than the default length. If not, the length of the text box is 4, otherwise it is the length of the input content.
However, this method can work well for English input, but it is not so easy to use when using the Chinese input method. Generally, the Chinese input method has English letters first, and the text is entered into the input box only after the space is pressed. This is a calculation error.
And this generally cannot meet the needs of most people, so I made another one and assembled it: Please refer to the code.
;(function ($) { $.fn.autoFit = function() { var $this = $(this); var oldWidth = parseInt($this.css('width')); $this.keydown(function (event) { var $this = $(this); setTimeout(function() { var val = $this.val().replace(/ /g, ' '); var fontSize = $this.css('font-size'); var fontFamily = $this.css('font-family'); var padding = $this.outerWidth() - $this.width(); var contentWidth = $('<span id="autowidthforinputtext">this).outerWidth(); var newWidth = ((contentWidth + padding) > oldWidth) ? (contentWidth + padding) : oldWidth; $('#autowidthforinputtext').remove(); $this.width(newWidth + 'px'); }, 0); }); return $this; };})(this['jQuery']);$('#txt').autoFit();
So I can work very well. Well, I am very satisfied. Test path. github source code
Let's take a look at the following:
1. This is the fn extension of Q. The advantage is that you can directly call my function using '.' For JQuery objects.
2. Use closures to avoid naming pollution and record the input width defined by the user at the beginning.
3. the clever use of the zero-latency setTimeout makes the plug-in well support the previous BUG caused by the Chinese input method. As for why, I have introduced in another article what is the setTimeout execution queue.
4. transcode the entered space.