Tworzenie obszaru tekstowego z automatyczną zmianą rozmiaru

Był kolejny wątek o tym , który próbowałem. Ale jest jeden problem: textarea nie zmniejsza się, jeśli usuniesz zawartość. Nie mogę znaleźć sposobu, aby zmniejszyć go do odpowiedniego rozmiaru - wartość {[2] } wraca jako Pełny rozmiar textarea, a nie jej zawartość.

Kod z tej strony znajduje się poniżej:

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}
Author: Racil Hilan, 2009-01-18

30 answers

To działa dla mnie (Firefox 3.6/4.0 i Chrome 10/11):

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();
}
textarea {
    border: 0 none white;
    overflow: hidden;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
}
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>

Jeśli chcesz spróbować na jsfiddle Zaczyna się od jednej linii i rośnie tylko dokładną ilość niezbędną. Jest ok dla pojedynczego textarea, ale chciałem napisać coś, w którym miałbym wiele, wiele, wiele takich textareas (mniej więcej tyle, ile normalnie miałoby się linie w dużym dokumencie tekstowym). W takim przypadku jest to bardzo powolne. (W Firefoksie jest szalenie wolny.) So I naprawdę chciałbym podejście, które wykorzystuje czysty CSS. Byłoby to możliwe za pomocą contenteditable, ale chcę, żeby to był zwykły tekst.

 175
Author: panzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-09 19:30:32

A COMPLETE YET SIMPLE SOLUTION

Zaktualizowano 23/08/2017 [12]} (Ulepszona obsługa przeglądarki dla telefonów komórkowych i tabletów)

Będzie działał następujący kod:

  • na wejściu kluczowym.
  • z wklejonym tekstem (kliknij prawym przyciskiem myszy & ctrl + v).
  • z wyciętym tekstem (kliknij prawym przyciskiem myszy & ctrl + x).
  • z wstępnie załadowanym tekstem.
  • z całym obszarem textarea (Wielowierszowe pole tekstowe).
  • Z Firefox (V31-55 testowany).
  • Z chromem (V37-60 testowany).
  • Z IE (V9-V11 testowany).
  • Z krawędzią (v14-V15 testowany).
  • Z iOS Safari.
  • Z Przeglądarką Android.
  • With JavaScript strict mode.
  • jest W3C zatwierdzona.
  • i jest usprawniony i wydajny.

Opcja 1 (z jQuery)

Ten kod wymaga jQuery i został przetestowany i działa z 1.7.2 - 3.2.1

Proste (Dodaj ten kod jquery do pliku skryptu głównego i zapomnij o nim.)

$('textarea').each(function () {
  this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This javascript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test na jsfiddle


Opcja 2 (czysty JavaScript)

Proste (Dodaj ten JavaScript do pliku głównego skryptu i zapomnij o tym.)

var tx = document.getElementsByTagName('textarea');
for (var i = 0; i < tx.length; i++) {
  tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test na jsfiddle


Opcja 3 (rozszerzenie jQuery)

Przydatne, jeśli chcesz zastosować dalsze łańcuchy do obszarów tekstowych, które chcesz mieć auto-rozmiar.

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ 'height': 'auto', 'overflow-y': 'hidden' })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on('input', function() {
        autoHeight_(this);
      });
    });
  }
});

Wywołaj z $('textarea').autoHeight()


AKTUALIZACJA TEXTAREA ZA POMOCĄ JAVASCRIPT

Podczas wstrzykiwania zawartości do obszaru tekstowego za pomocą JavaScript Dodaj następujący kod, aby wywołać funkcję w opcji 1.

$('textarea').trigger('input');
 234
Author: DreamTeK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 13:01:31

JQuery solution dostosuj css do swoich wymagań

Css...

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}

Javascript...

// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();

Lub alternatywa dla jQuery 1.7+...

// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

Stworzyłem skrzypce z absolutnym minimum stylizacji jako punkt wyjścia do Twoich eksperymentów... http://jsfiddle.net/53eAy/951/

 61
Author: chim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-14 15:18:47
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea autoresize</title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }

    var te = document.querySelector('textarea');
    te.addEventListener('input', resizeTextarea);
    </script>
</head>
<body>
    <textarea></textarea>
</body>
</html>
Testowane w Firefoksie 14 i Chromium 18. Liczby 24 i 12 są dowolne, sprawdź, co najbardziej Ci odpowiada.

Można obejść się bez tagów style i script, ale staje się trochę bałagan imho (to jest stary styl HTML+JS i nie jest zachęcany).

<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>

Edit: zmodernizowany kod. Zmieniono atrybut onkeyup na addEventListener.
Edit: keydown działa lepiej niż keyup
Edit: declare funkcja przed użyciem
Edit: wejście działa lepiej niż keydown (thnx @WASD42 & @MA-Maddin)

Jsfiddle

 28
Author: GijsjanB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 09:55:44

Najlepsze rozwiązanie (działa i jest krótkie) dla mnie to:

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

Działa jak czar bez mrugania pastą (również myszką), cięcia, wchodzenia i kurczy się do odpowiedniego rozmiaru.

Proszę spojrzeć na jsFiddle .

 21
Author: vatavale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-05 10:31:24

Używasz wyższej wartości bieżącego clientHeight i przewijania zawartości. Gdy zmniejszysz przewijanie, usuwając zawartość, obszar obliczony nie może się zmniejszyć, ponieważ clientHeight, wcześniej ustawiony przez styl.wysokość, trzyma ją otwartą. Możesz zamiast tego przyjąć max () przewijania i minimalną wartość wysokości, którą wcześniej zdefiniowałeś lub obliczyłeś z textarea.rzędy.

Ogólnie rzecz biorąc, prawdopodobnie nie powinieneś polegać na przewijaniu w formularzach. Apart ponieważ scrollHeight jest tradycyjnie mniej wspierany niż niektóre z innych rozszerzeń IE, HTML / CSS nie mówi nic o tym, jak formanty są implementowane wewnętrznie i nie masz gwarancji, że scrollHeight będzie cokolwiek znaczącego. (Tradycyjnie niektóre przeglądarki używały do tego zadania widżetów systemu operacyjnego, co uniemożliwiało interakcję CSS i DOM na ich wewnętrznej stronie.) Przynajmniej powąchaj dla scrollheight/clientHeight ' s existance przed próbą włączenia efektu.

Inna możliwa alternatywa podejściem, aby uniknąć problemu, jeśli jest to ważne, że działa szerzej, może być użycie ukrytego div o tej samej szerokości co textarea i ustawionego w tej samej czcionce. W keyUp, kopiujesz tekst z textarea do węzła tekstowego w ukrytym div (pamiętając, aby zastąpić' \n 'z przerwaniem linii i odpowiednio escape'

 16
Author: bobince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-18 00:57:13

Jeśli nie musisz obsługiwać IE8 możesz użyć zdarzenia input:

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}

Teraz wystarczy dodać trochę CSS i gotowe:

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

Użycie:

<textarea autoresize>Type here and I’ll resize.</textarea>

Możesz przeczytać więcej o tym, jak to działa na moim blogu.

 14
Author: We are hiring Elm and JS devs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-25 14:27:49

Autosize

Https://github.com/jackmoore/autosize

Just works, standalone, jest popularny (3.0 K+ gwiazd GitHub na Październik 2018), dostępny na cdnjs ) i lekki (~3.5 k). Demo:

<textarea id="autosize" style="width:200px;">a
J   b
c</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js"></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>

BTW, jeśli używasz edytora ACE, użyj maxLines: Infinity: Automatycznie dostosuj wysokość do zawartości w edytorze Ace Cloud 9

 9
Author: Ciro Santilli 新疆改造中心 六四事件 法轮功,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-06 20:52:48

Czy ktoś rozważał contenteditable? Bez wygłupiania się z przewijaniem, a jedynym JS, który mi się podoba, jest to, że planujesz zapisać dane na rozmyciu... i najwyraźniej jest kompatybilny ze wszystkimi popularnymi przeglądarkami: http://caniuse.com/#feat=contenteditable

Po prostu wystylizuj go tak, aby wyglądał jak pole tekstowe i automatycznie się ustawia... Ustaw jego min-height jako preferowaną wysokość tekstu i miej na nim.

Fajne w tym podejściu jest to, że można zapisać i tagi na niektórych z przeglądarki.

Http://jsfiddle.net/gbutiri/v31o8xfo/

<style>
.autoheight {
    min-height: 16px;
    font-size: 16px;
    margin: 0;
    padding: 10px;
    font-family: Arial;
    line-height: 16px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    overflow: hidden;
    resize: none;
    border: 1px solid #ccc;
    outline: none;
    width: 200px;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on('blur','.autoheight',function(e) {
    var $this = $(this);
    // The text is here. Do whatever you want with it.
    console.log($this.html());
});

</script>
<div class="autoheight contenteditable" contenteditable="true">Mickey Mouse</div>
 6
Author: Webmaster G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-16 20:09:28

Użyłem poniższego kodu dla wielu tekstów. Działa dobrze w Chrome 12, Firefox 5 i IE 9, nawet z delete, cut i wklej działań wykonywanych w teks.

<!-- language: lang-html -->
<style type='text/css'>
textarea { border:0 none; overflow:hidden; outline:none; background-color:#eee }
</style>
<textarea style='height:100px;font-family:arial' id="txt1"></textarea>
<textarea style='height:125px;font-family:arial' id="txt2"></textarea>
<textarea style='height:150px;font-family:arial' id="txt3"></textarea>
<textarea style='height:175px;font-family:arial' id="txt4"></textarea>
<script type='text/javascript'>
function attachAutoResizeEvents()
{   for(i=1;i<=4;i++)
    {   var txtX=document.getElementById('txt'+i)
        var minH=txtX.style.height.substr(0,txtX.style.height.indexOf('px'))
        txtX.onchange=new Function("resize(this,"+minH+")")
        txtX.onkeyup=new Function("resize(this,"+minH+")")
        txtX.onchange(txtX,minH)
    }
}
function resize(txtX,minH)
{   txtX.style.height = 'auto' // required when delete, cut or paste is performed
    txtX.style.height = txtX.scrollHeight+'px'
    if(txtX.scrollHeight<=minH)
        txtX.style.height = minH+'px'
}
window.onload=attachAutoResizeEvents
</script>
 4
Author: Nikunj Bhatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-23 15:10:50

Następujące prace do cięcia, wklejania itp., niezależnie od tego, czy te działania są z myszy, skrót klawiaturowy, wybierając opcję z paska menu ... kilka odpowiedzi przyjmuje podobne podejście, ale nie uwzględniają rozmiaru pudełka, dlatego nieprawidłowo stosują styl overflow: hidden.

Wykonuję następujące czynności, które również działają dobrze z max-height i rows dla minimalnej i maksymalnej wysokości.

function adjust() {
  var style = this.currentStyle || window.getComputedStyle(this);
  var boxSizing = style.boxSizing === 'border-box'
      ? parseInt(style.borderBottomWidth, 10) +
        parseInt(style.borderTopWidth, 10)
      : 0;
  this.style.height = '';
  this.style.height = (this.scrollHeight + boxSizing) + 'px';
};

var textarea = document.getElementById("ta");
if ('onpropertychange' in textarea) { // IE
  textarea.onpropertychange = adjust;
} else if ('oninput' in textarea) {
  textarea.oninput = adjust;
}
setTimeout(adjust.bind(textarea));
textarea {
  resize: none;
  max-height: 150px;
  border: 1px solid #999;
  outline: none;
  font: 18px sans-serif;
  color: #333;
  width: 100%;
  padding: 8px 14px;
  box-sizing: border-box;
}
<textarea rows="3" id="ta">
Try adding several lines to this.
</textarea>

Dla kompletności absolutnej, należy wywołać funkcję adjust w jeszcze kilku okolicznościach:

  1. zdarzenia zmiany rozmiaru okna, jeśli szerokość textarea Zmienia się wraz ze zmianą rozmiaru okna lub innymi zdarzeniami, które zmieniają szerokość obszaru tekstowego
  2. gdy atrybut textarea's display style zmienia się, np. gdy przechodzi z none (hidden) do block
  3. gdy wartość textarea jest zmieniana programowo

Zauważ, że używanie window.getComputedStyle lub otrzymywanie currentStyle Może być nieco kosztowne obliczeniowo, więc zamiast tego możesz chcieć buforować wynik.

Działa na IE6, więc mam nadzieję, że to wystarczająco dobre wsparcie.

 4
Author: Joseph Nields,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-24 17:14:43

Jest nieco inne podejście.

<div style="position: relative">
  <pre style="white-space: pre-wrap; word-wrap: break-word"></pre>
  <textarea style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></textarea>
</div>

Chodzi o to, aby skopiować tekst z textarea do pre i pozwolić CSS upewnić się, że mają ten sam rozmiar.

Zaletą jest to, że frameworki prezentują proste narzędzia do przenoszenia tekstu bez dotykania żadnych zdarzeń. Mianowicie w AngularJS dodałbyś ng-model="foo" ng-trim="false" do textarea i {[5] } do pre. Zobacz .

Upewnij się, że pre ma taką samą czcionkę jak textarea.

 3
Author: Karolis Juodelė,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-17 14:45:33

Trochę poprawione. Doskonale sprawdza się w Operze

  $('textarea').bind('keyup keypress', function() {
      $(this).height('');
      var brCount = this.value.split('\n').length;
      this.rows = brCount+1; //++ To remove twitching
      var areaH = this.scrollHeight,
          lineHeight = $(this).css('line-height').replace('px',''),
          calcRows = Math.floor(areaH/lineHeight);
      this.rows = calcRows;
  });
 2
Author: artnik-pro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-19 12:29:54

Znam krótki i poprawny sposób realizacji tego z jquery.No dodatkowe ukryte div potrzebne i działa w większości przeglądarek

<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){
var h=$(this);
h.height(60).height(h[0].scrollHeight);//where 60 is minimum height of textarea
});});

</script>
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-24 08:46:12

Nie wiem, czy ktoś o tym wspomniał, ale w niektórych przypadkach można zmienić rozmiar wysokości z atrybutem rows

textarea.setAttribute('rows',breaks);

Demo

 2
Author: h0mayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-11 12:48:45

Oto dyrektywa angularjs dla odpowiedzi panziego.

 module.directive('autoHeight', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element = element[0];
                var resize = function(){
                    element.style.height = 'auto';
                    element.style.height = (element.scrollHeight)+'px';
                };
                element.addEventListener('change', resize, false);
                element.addEventListener('cut',    resize, false);
                element.addEventListener('paste',  resize, false);
                element.addEventListener('drop',   resize, false);
                element.addEventListener('keydown',resize, false);

                setTimeout(resize, 100);
            }
        };
    });

HTML:

<textarea ng-model="foo" auto-height></textarea>
 2
Author: chrmcpn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-28 20:48:46

Jako inne podejście, możesz użyć <span>, który automatycznie dostosowuje swój rozmiar. Musisz dodać właściwość contenteditable="true" i gotowe:

div {
  width: 200px;
}

span {
  border: 1px solid #000;
  padding: 5px;
}
<div>
  <span contenteditable="true">This text can be edited by the user</span>
</div>

Jedyny problem z tym podejściem polega na tym, że jeśli chcesz przesłać wartość jako część formularza, musisz to zrobić samodzielnie w JavaScript. Jest to stosunkowo łatwe. Na przykład, można dodać ukryte pole i w zdarzeniu onsubmit formularza przypisać wartość {[5] } do ukryte pole, które zostanie automatycznie przesłane wraz z formularzem.

 2
Author: Racil Hilan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-24 14:40:25

Niektóre odpowiedzi tutaj nie uwzględniają padding.

Zakładając, że masz maxHeight, którego nie chcesz przechodzić, u mnie to zadziałało:

    // obviously requires jQuery

    // element is the textarea DOM node

    var $el = $(element);
    // inner height is height + padding
    // outerHeight includes border (and possibly margins too?)
    var padding = $el.innerHeight() - $el.height();
    var originalHeight = $el.height();

    // XXX: Don't leave this hardcoded
    var maxHeight = 300;

    var adjust = function() {
        // reset it to the original height so that scrollHeight makes sense
        $el.height(originalHeight);

        // this is the desired height (adjusted to content size)
        var height = element.scrollHeight - padding;

        // If you don't want a maxHeight, you can ignore this
        height = Math.min(height, maxHeight);

        // Set the height to the new adjusted height
        $el.height(height);
    }

    // The input event only works on modern browsers
    element.addEventListener('input', adjust);
 1
Author: hasen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-01 12:56:05

Jeszcze prostsze, czystsze podejście jest takie:

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

// oraz CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

Wystarczy dodać klasę .auto-height do dowolnej textarea, którą chcesz kierować.

Testowane w FF, Chrome i Safari. Daj mi znać, jeśli to nie zadziała dla Ciebie, z jakiegokolwiek powodu. Ale to jest najczystszy i najprostszy sposób, jaki znalazłem, aby to zadziałało. I to działa świetnie! : D

 1
Author: revive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-22 06:43:11

Ten kod działa do wklejania i wybierz Usuń również.

onKeyPressTextMessage = function(){
			var textArea = event.currentTarget;
    	textArea.style.height = 'auto';
    	textArea.style.height = textArea.scrollHeight + 'px';
};
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>

Oto JSFiddle

 1
Author: Kurenai Kunai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-14 08:59:19

Po prostu użyj <pre> </pre> z niektórymi stylami, takimi jak:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }
 1
Author: Liber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-30 07:42:01

Oto co zrobiłem podczas korzystania z MVC HTML Helper dla TextArea. Miałem sporo elementów textarea, więc musiałem je odróżnić za pomocą ID modelu.

 @Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })

I w skrypcie Dodano to:

   function resizeTextBox(ID) {            
        var text = document.getElementById('text' + ID);
        text.style.height = 'auto';
        text.style.height = text.scrollHeight + 'px';            
    }

Przetestowałem go na IE10 i Firefox23

 0
Author: gunnerz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-11 13:38:19

Możesz użyć tego kodu:

Coffescript:

jQuery.fn.extend autoHeightTextarea: ->
  autoHeightTextarea_ = (element) ->
    jQuery(element).css(
      'height': 'auto'
      'overflow-y': 'hidden').height element.scrollHeight

  @each ->
    autoHeightTextarea_(@).on 'input', ->
      autoHeightTextarea_ @

$('textarea_class_or_id`').autoHeightTextarea()

Javascript

jQuery.fn.extend({
  autoHeightTextarea: function() {
    var autoHeightTextarea_;
    autoHeightTextarea_ = function(element) {
      return jQuery(element).css({
        'height': 'auto',
        'overflow-y': 'hidden'
      }).height(element.scrollHeight);
    };
    return this.each(function() {
      return autoHeightTextarea_(this).on('input', function() {
        return autoHeightTextarea_(this);
      });
    });
  }
});

$('textarea_class_or_id`').autoHeightTextarea();
 0
Author: Darex1991,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-08 15:03:49

Dla tych, którzy chcą, aby textarea była automatycznie zmieniana na szerokość i wysokość:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

JQuery:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

Codepen:

Http://codepen.io/anon/pen/yNpvJJ

Zdrówko, zdrówko]}
 0
Author: Goon Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-29 04:51:34

Rozwiązaniem jQuery jest ustawienie wysokości obszaru tekstowego na "auto", sprawdzenie przewijania, a następnie dostosowanie wysokości obszaru tekstowego do tego, za każdym razem, gdy zmienia się obszar tekstowy (JSFiddle):

$('textarea').on( 'input', function(){
    $(this).height( 'auto' ).height( this.scrollHeight );
});

Jeśli dynamicznie dodajesz tekst (przez AJAX lub cokolwiek innego), możesz to dodać do swojego $(dokumentu).gotowe, aby upewnić się, że wszystkie teksty z klasą "autoheight" są utrzymywane na tej samej wysokości co ich zawartość:

$(document).on( 'input', 'textarea.autoheight', function() {
    $(this).height( 'auto' ).height( this.scrollHeight );
});

Przetestowano i działa w Chrome, Firefox, Opera i IE. Obsługuje również cięcie i wklejanie, długie słowa itp.

 0
Author: patrick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-02 10:25:48

Możesz użyć tego fragmentu kodu, aby obliczyć liczbę wierszy, których potrzebuje obszar tekstowy:

textarea.rows = 1;
    if (textarea.scrollHeight > textarea.clientHeight)
      textarea.rows = textarea.scrollHeight / textarea.clientHeight;

Oblicz go na zdarzeniach input i window:resize, Aby uzyskać efekt auto-resize. Przykład w języku Angular:

Kod szablonu:

<textarea rows="1" reAutoWrap></textarea>

Automatyczne zawijanie.dyrektywa.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'textarea[reAutoWrap]',
})
export class AutoWrapDirective {

  private readonly textarea: HTMLTextAreaElement;

  constructor(el: ElementRef) {
    this.textarea = el.nativeElement;
  }

  @HostListener('input') onInput() {
    this.resize();
  }

  @HostListener('window:resize') onChange() {
    this.resize();
  }

  private resize() {
    this.textarea.rows = 1;
    if (this.textarea.scrollHeight > this.textarea.clientHeight)
      this.textarea.rows = this.textarea.scrollHeight / this.textarea.clientHeight;
  }

}
 0
Author: André,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-14 13:22:14

Natywne rozwiązanie Javascript bez migotania w Firefoksie i szybsze niż metoda z clientheight...

1) Dodaj selektor div.textarea do wszystkich selektorów zawierających textarea. Nie zapomnij dodać box-sizing: border-box;

2) Dołącz ten skrypt:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

Testowane na IE11, Firefox i Chrome.

To rozwiązanie tworzy div podobne do twojego textarea, w tym tekst wewnętrzny i mierzy wysokość.

 0
Author: 18C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-18 05:49:56

Maketextarearezable, który używa qQuery

function MakeTextAreaResisable(id) {
    var o = $(id);
    o.css("overflow-y", "hidden");

    function ResizeTextArea() {
        o.height('auto');
        o.height(o[0].scrollHeight);
    }

    o.on('change', function (e) {
        ResizeTextArea();
    });

    o.on('cut paste drop keydown', function (e) {
        window.setTimeout(ResizeTextArea, 0);
    });

    o.focus();
    o.select();
    ResizeTextArea();
}
 0
Author: Igor Krupitsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-19 18:01:48

Żadna z odpowiedzi nie działa. Ale ten działa na mnie: https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content

$('#content').on( 'change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();
 0
Author: Kim Homann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-04 11:51:57

Przetestowałem skrypt w popularnych przeglądarkach i nie powiódł się w Chrome i Safari. Dzieje się tak z powodu stale aktualizowanej zmiennej scrollHeight.

Zastosowałem skrypt jQuery i dodałem Chrome fix

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}
 -1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-07 14:01:05