有时候我们需要textarea高度随着行数多少进行跟随改变,而不是出现滚动条,以下方法和新浪微博的发布框一模一样效果,本人已用在项目中,分享出来给大家
function autoTextarea(options) {
var defaults={
$elem:'', //jquery对象textarea
extra:'', //额外增加高度
maxHeight:'', //最大高度,默认无限
callback:function($this,opts){}//高度改变之后的回调
};
var opts=$.extend({}, defaults , options || {});
opts.extra = opts.extra || 0;
var elem=opts.$elem[0];
var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
addEvent = function (type, callback) {
elem.addEventListener ?
elem.addEventListener(type, callback, false) :
elem.attachEvent('on' + type, callback);
},
getStyle = elem.currentStyle ? function (name) {
var val = elem.currentStyle[name];
if (name === 'height' && val.search(/px/i) !== 1) {
var rect = elem.getBoundingClientRect();
return rect.bottom - rect.top - parseFloat(getStyle('paddingTop')) - parseFloat(getStyle('paddingBottom')) + 'px';
};
return val;
} : function (name) {
return getComputedStyle(elem, null)[name];
},
minHeight = parseFloat(getStyle('height'));
elem.style.resize = 'none';
var change = function () {
var scrollTop, height, padding = 0, style = elem.style;
if (elem._length === elem.value.length) return;
elem._length = elem.value.length;
if (!isFirefox && !isOpera) {
padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
};
scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
elem.style.height = minHeight + 'px';
if (elem.scrollHeight > minHeight) {
if (opts.maxHeight && elem.scrollHeight > opts.maxHeight) {
height = opts.maxHeight - padding;
style.overflowY = 'auto';
} else {
height = elem.scrollHeight - padding;
style.overflowY = 'hidden';
};
style.height = height + opts.extra + 'px';
scrollTop += parseInt(style.height) - elem.currHeight;
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
elem.currHeight = parseInt(style.height);
};
if(typeof opts.callback=='function'){
opts.callback($(elem),opts);
}
};
addEvent('propertychange', change);
addEvent('input', change);
addEvent('focus', change);
change();
}