Плагін jQuery:
<script>
(function ($) {
$.fn.autoGrow = function (options) {
const settings = $.extend({
maxLines: 10
}, options);
return this.each(function () {
const el = this;
const $el = $(el);
const style = window.getComputedStyle(el);
let lineHeight = parseFloat(style.lineHeight);
// fallback if line-height is "normal"
if (isNaN(lineHeight)) {
const temp = document.createElement('span');
temp.style.font = style.font;
temp.innerHTML = 'M';
document.body.appendChild(temp);
lineHeight = temp.offsetHeight;
document.body.removeChild(temp);
}
const maxHeight = lineHeight * settings.maxLines;
$el.css({
resize: 'none',
overflowY: 'hidden',
maxHeight: maxHeight + 'px'
});
const resize = () => {
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
if (el.scrollHeight > maxHeight) {
el.style.height = maxHeight + 'px';
el.style.overflowY = 'auto';
} else {
el.style.overflowY = 'hidden';
}
};
resize();
$el.on('input.autoGrow', resize);
});
};
})(jQuery);
</script>
Виклик:
$('textarea').autoGrow({
maxLines: 10
});