Увеличивать textarea при необходимости

07.01.20 17:47:41 07.01.20 17:55:33 8
Вариант 1 <script> var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on'+event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function init () { var text = document.getElementById('text'); function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+'px'; } /* 0-timeout to get the already changed text */ function delayedResize () { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); text.focus(); text.select(); resize(); } </script> <style> textarea { border: 0 none white; overflow: hidden; padding: 0; outline: none; background-color: #D0D0D0; } </style> <body onload="init();"> <textarea rows="1" style="height:1em;" id="text"></textarea> </body> *Источник: https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize/5346855#5346855 Вариант 2: <script> let ghost = $('#ghost'); $('textarea').on('keypress change', function(){ let text = $(this).val(); ghost.text(text); let ghostHeight = ghost.height(); $(this).height(ghostHeight); console.clear(); console.info(`Высота textarea == ${Math.ceil(ghostHeight*100)/100}px`); }); </script> <style> @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap'); body { font-family: 'Roboto', sans-serif; font-size: 14px; line-height: 1.45; } textarea, #ghost { display: block; width: 200px; min-height: 50px; overflow: hidden; font: inherit; padding: 5px; box-sizing: border-box; word-break: break-word; } textarea { border: 1px solid #aaa; border-radius: 5px; background: transparent; color: #333; resize: none; transition: height .05s linear; } #ghost { display: none; position: absolute; left: -1000px; z-index: -1; border: 1px solid transparent; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form_input"><textarea class="f_input" placeholder="Описание"></textarea></div> *Источник: https://ru.stackoverflow.com/questions/1066877/Увеличивать-textarea-при-необходимости