In order to improve the user experience, I thought about whether I could write a plug-in using jQuery during my lunch break. I thought I might as well do it, and sure enough, I realized this function. When writing this plug-in, I subconsciously thought that someone should have written such a plug-in on the Internet, but I did not search for it. If you are interested, you can look for it. Below is the source code of the plugin.
Source code
;(function($) {
$.fn.autoSizeText = function(settings) {
var _defaultSettings = {min:20,max:40};
var _settings = $.extend(_defaultSettings, settings);
var _handler = function() {
jQuery(this).keyup(function() {
if (jQuery(this).attr("type") != 'text') {
return false;
}
jQuery(this).attr("size", _settings.min);
var actLength = jQuery(this).val().length;
if (actLength > _settings.min && actLength < _settings.max) {
jQuery(this).attr("size", actLength 1);
} else if (actLength <= _settings.min) {
jQuery(this). attr("size", _settings.min);
}
});
};
return this.each(_handler);
};
})(jQuery) ;
Call the method: $(':text').autoSizeText();.
This plug-in has two optional parameters: max (set the maximum size of the text box, the size will not increase beyond this value, the default value is 40) and min (set the minimum size of the text box, which is also the initial size of the text box) , the default value is 20), which can be modified when calling.
For example: $(':text').autoSizeText({min:24,max:35});
$(':text').autoSizeText({max:35});//min None Set, take the default value 20
$(':text').autoSizeText({min:12});//max is not set, take the default value 40
You can continue to expand on this basis, for example Support textarea.
enjoy it!