🔎

Як зробити, щоб textarea автоматично збільшувалася лише до 10 рядків, як у Facebook?

У мене є скрипт autosize, який збільшує поле textarea. Але він збільшує поле до безкінечності. Який мені використати скрипт, щоб було як у Facebook, тобто поле автоматично збільшувалося на рядків 10 автоматично, а далі з’являвся вертикальний скролінг?
jquery
1 відповідь
  • Олег
    Плагін 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
    });