最近项目应要求,需要让textarea高度随输入自适应,那么走起吧!
html
<textarea></textarea>
css
textarea {
width: 200px;
height: 100px;
min-height: 100px;
overflow: hidden;
}
JS
/**
* 让textarea高度随输入自适应
* @param {[[Type]]} selector 选择器
* @param {[[Type]]} callback
*/
var bindTextChange = function (selector, callback) {
var $selector = $(selector);
var _IE = (function() {
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : false;
})();
if (_IE && _IE < 9) {
$selector.on('propertychange', function() {
window.event.propertyName === 'value' && callback.call(this);
});
} else {
$selector.on('input', callback);
if (_IE === 9) {
var callbackWrapper = function() {
callback.call($selector[0]);
}
$selector.on('focus', function() {
document.addEventListener('selectionchange', callbackWrapper);
}).on('blur', function() {
document.removeEventListener('selectionchange', callbackWrapper);
});
}
}
}
var $textarea = $('textarea');
var paddingTop = parseFloat($textarea.css('padding-top'));
var paddingBottom = parseFloat($textarea.css('padding-bottom'));
var minHeight = parseFloat($textarea.css('min-height'));
bindTextChange('textarea', function() {
$(this).height(minHeight).height(this.scrollHeight - paddingTop - paddingBottom);
});
|