SoFunction
Updated on 2025-02-28

The text box adapts to the height of the input content


/**
* The text box adapts to the height according to the input content
* @author tang bin
* @version 0.3
* @see /?p=1489
* @param {HTMLElement} Input box element
* @param {Number} Set the distance between the cursor and the input box (default 20)
* @param {Number} Set maximum height (optional)
*/
var autoTextarea = function (elem, extra, maxHeight) {
extra = extra || 20;
var isFirefox = !! || 'mozInnerScreenX' in window,
isOpera = !! && !!().indexOf('Opera'),
addEvent = function (type, callback) {
?
(type, callback, false) :
('on' + type, callback);
},
getStyle = ? function (name) {
var val = [name];
if (name === 'height' && (/px/i) !== 1) {
var rect = ();
return - -
parseFloat(getStyle('paddingTop')) -
parseFloat(getStyle('paddingBottom')) + 'px';
};
return val;
} : function (name) {
return getComputedStyle(elem, null)[name];
},
minHeight = parseFloat(getStyle('height'));
= = 'none';
var change = function () {
var scrollTop, height,
padding = 0,
style = ;
if (elem._length === ) return;
elem._length = ;
if (!isFirefox && !isOpera) {
padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
};
scrollTop = || ;
= minHeight + 'px';
if ( > minHeight) {
if (maxHeight && > maxHeight) {
height = maxHeight - padding;
= 'auto';
} else {
height = - padding;
= 'hidden';
};
= height + extra + 'px';
scrollTop += parseInt() - ;
= scrollTop;
= scrollTop;
= parseInt();
};
};
addEvent('propertychange', change);
addEvent('input', change);
addEvent('focus', change);
change();
};