Creazione di un'area di testo con ridimensionamento automatico
-
19-08-2019 - |
Domanda
C'era un'altra discussione su questo , che ho provato. Ma c'è un problema: textarea
non si riduce se si elimina il contenuto. Non riesco a trovare un modo per ridurlo alla dimensione corretta: il valore clientHeight
ritorna come dimensione intera di <=>, non come contenuto.
Il codice da quella pagina è in basso:
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 )
};
}
Soluzione
Questo funziona per me (Firefox 3.6 / 4.0 e 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>
Se vuoi provarlo su jsfiddle
Inizia con una sola riga e cresce solo la quantità esatta necessaria. Va bene per un singolo textarea
, ma volevo scrivere qualcosa in cui avrei molti molti molti contenteditable
s (circa quanto uno avrebbe normalmente linee in un grande documento di testo). In quel caso è molto lento. (In Firefox è follemente lento.) Quindi mi piacerebbe davvero un approccio che utilizza CSS puro. Questo sarebbe possibile con <=>, ma voglio che sia solo in chiaro.
Altri suggerimenti
UNA SOLUZIONE SEMPLICE ANCORA COMPLETA
Aggiornato 07/05/2019 (Supporto browser migliorato per cellulari e tablet)
Il seguente codice funzionerà:
- Inserimento chiave.
- Con testo incollato (tasto destro & amp; ctrl + v).
- Con testo tagliato (tasto destro & amp; ctrl + x).
- Con testo precaricato.
- Con tutto il sito (caselle di testo su più righe) di textarea.
- Con Firefox (testato v31-67).
- Con Chrome (testato v37-74).
- Con IE (v9-v11 testato).
- Con Edge (testato v14-v18).
- Con IOS Safari .
- Con Browser Android .
- Con JavaScript modalità rigorosa .
- w3c è validato.
- Ed è snello ed efficiente.
OPZIONE 1 (Con jQuery)
Questa opzione richiede jQuery ed è stata testata e funziona con 1.7.2 - 3.3.1
Semplice (Aggiungi questo codice jquery al tuo file di script principale e dimenticalo.)
$('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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.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>
OPZIONE 2 (JavaScript puro)
Semplice (Aggiungi questo JavaScript al tuo file di script principale e dimenticalo.)
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>
OPZIONE 3 (estensione jQuery)
Utile se si desidera applicare un ulteriore concatenamento alle aree di testo che si desidera ridimensionare automaticamente.
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);
});
});
}
});
Richiama con $('textarea').autoHeight()
AGGIORNAMENTO DI TEXTAREA VIA JAVASCRIPT
Quando si inietta contenuto in un'area di testo tramite JavaScript, aggiungere il seguente codice per richiamare la funzione nell'opzione 1.
$('textarea').trigger('input');
soluzione jQuery regolare il CSS in base alle proprie esigenze
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();
O alternativa a jQuery 1.7 + ...
// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
$(this).height( 0 );
$(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();
Ho creato un violino con lo stile minimo assoluto come punto di partenza per i tuoi esperimenti ... http://jsfiddle.net/53eAy/951/
<!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>
Testato in Firefox 14 e Chromium 18. I numeri 24 e 12 sono arbitrari, prova per vedere cosa ti si addice meglio.
Potresti fare a meno dello stile e dei tag di script, ma diventa un imho un po 'disordinato (questo è HTML + JS vecchio stile e non è incoraggiato).
<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>
Modifica: codice modernizzato. Attributo onkeyup modificato in addEventListener.
Modifica: il keydown funziona meglio del keyup
Modifica: dichiara la funzione prima di usare
Modifica: l'input funziona meglio del keydown (thnx @ WASD42 & Amp; @ MA-Maddin)
La soluzione migliore (funziona ed è breve) per me è:
$(document).on('input', 'textarea', function () {
$(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
});
Funziona come un incantesimo senza battere ciglio con incolla (anche con il mouse), tagliare, entrare e si restringe alla giusta dimensione.
Dai un'occhiata a jsFiddle .
Stai utilizzando il valore più alto dell'attuale clientHeight e del contenuto scrollHeight. Quando si riduce lo scrollHeight rimuovendo il contenuto, l'area calcolata non può ridursi perché clientHeight, precedentemente impostato da style.height, lo tiene aperto. Potresti invece prendere un max () di scrollHeight e un valore di altezza minima che hai predefinito o calcolato da textarea.rows.
In generale probabilmente non dovresti davvero fare affidamento su scrollHeight sui controlli del modulo. A parte il fatto che scrollHeight è tradizionalmente meno ampiamente supportato rispetto ad alcune delle altre estensioni di IE, HTML / CSS non dice nulla su come i controlli dei moduli sono implementati internamente e non sei garantito che scrollHeight sarà qualcosa di significativo. (Tradizionalmente alcuni browser hanno utilizzato i widget del sistema operativo per l'attività, rendendo impossibile l'interazione CSS e DOM sui loro interni.) Almeno annusa l'esistenza di scrollHeight / clientHeight prima di provare ad abilitare l'effetto.
Un altro possibile approccio alternativo per evitare il problema se è importante che funzioni in modo più ampio potrebbe essere quello di utilizzare un div nascosto dimensionato alla stessa larghezza dell'area di testo e impostato nello stesso carattere. Al keyup, copi il testo dall'area di testo in un nodo di testo in div nascosto (ricordando di sostituire '\ n' con un'interruzione di riga e di scappare '& Lt;' / '& Amp;' correttamente se stai usando innerHTML). Quindi semplicemente misurando l'offset del divHeight ti darà l'altezza di cui hai bisogno.
Se non & # 8217; t è necessario supportare IE8 è possibile utilizzare l'evento 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));
}
Ora devi solo aggiungere alcuni CSS e hai finito:
textarea[autoresize] {
display: block;
overflow: hidden;
resize: none;
}
Utilizzo:
<textarea autoresize>Type here and I’ll resize.</textarea>
Puoi leggere di più su come funziona sul mio post sul blog .
autosize
https://github.com/jackmoore/autosize
Funziona solo, standalone, è popolare (3.0k + stelle GitHub a partire da ottobre 2018), disponibile su cdnjs ) e leggero (~ 3.5k). 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>
A proposito, se si utilizza l'editor ACE, utilizzare maxLines: Infinity
: Regola automaticamente l'altezza in base ai contenuti nell'editor di Ace Cloud 9
Qualcuno ha considerato contendibile? Non scherzare con lo scorrimento, e l'unico JS che mi piace a riguardo è se hai intenzione di salvare i dati su sfocatura ... e apparentemente, è compatibile su tutti i browser più diffusi: http://caniuse.com/#feat=contenteditable
Modificalo in modo che appaia come una casella di testo e si ridimensiona automaticamente ... Imposta l'altezza minima dell'altezza del testo preferita e utilizzala.
La cosa interessante di questo approccio è che puoi salvare e taggare su alcuni browser.
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>
Ho usato il seguente codice per più textareas. Funziona bene in Chrome 12, Firefox 5 e IE 9, anche con le azioni di eliminazione, taglia e incolla eseguite nelle aree di testo.
<!-- 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>
C'è un approccio leggermente diverso.
<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>
L'idea è di copiare il testo da textarea
in pre
e lasciare che i CSS si assicurino che abbiano le stesse dimensioni.
Il vantaggio è che i framework presentano semplici strumenti per spostare il testo senza toccare alcun evento. Vale a dire, in AngularJS aggiungere un ng-model="foo" ng-trim="false"
a ng-bind="foo + '\n'"
e <=> a <=>. Guarda un violino .
Assicurati solo che <=> abbia le stesse dimensioni del carattere di <=>.
Le seguenti operazioni funzionano per tagliare, incollare, ecc., indipendentemente dal fatto che tali azioni provengano dal mouse, una scorciatoia da tastiera, selezionando un'opzione da una barra dei menu ... diverse risposte adottano un approccio simile ma non tengono conto per il ridimensionamento delle scatole, motivo per cui applicano erroneamente lo stile overflow: hidden
.
Faccio quanto segue, che funziona bene anche con max-height
e rows
per altezza minima e massima.
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>
Per completezza assoluta, è necessario chiamare la funzione adjust
in alcune altre circostanze:
- Eventi di ridimensionamento della finestra, se la larghezza di
textarea
cambia con il ridimensionamento della finestra o altri eventi che cambiano la larghezza dell'area di testo - Quando cambia l'attributo di stile
display
none
, ad es. quando va dablock
(nascosto) awindow.getComputedStyle
- Quando il valore di
currentStyle
viene modificato a livello di programmazione
Nota che usare <=> o ottenere <=> può essere un po 'costoso dal punto di vista computazionale, quindi potresti voler memorizzare il risultato nella cache.
Funziona per IE6, quindi spero davvero che sia abbastanza buono supporto.
Come approccio diverso, puoi usare un <span>
che regola automaticamente le sue dimensioni. Dovrai renderlo modificabile aggiungendo la proprietà contenteditable="true"
e il gioco è fatto:
div {
width: 200px;
}
span {
border: 1px solid #000;
padding: 5px;
}
<div>
<span contenteditable="true">This text can be edited by the user</span>
</div>
L'unico problema con questo approccio è che se desideri inviare il valore come parte del modulo, dovrai farlo da solo in JavaScript. Farlo è relativamente facile. Ad esempio, puoi aggiungere un campo nascosto e nell'evento onsubmit
del modulo assegnare il valore di span
al campo nascosto che verrà quindi automaticamente inviato con il modulo.
Correzioni di bit. Funziona perfettamente in Opera
$('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;
});
Conosco un modo breve e corretto di implementarlo con jquery. Non sono necessari div nascosti extra e funziona nella maggior parte dei browser
<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>
Non so se qualcuno menziona in questo modo, ma in alcuni casi è possibile ridimensionare l'altezza con le righe Attributo
textarea.setAttribute('rows',breaks);
Ecco una direttiva angularjs per la risposta di Panzi.
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>
Puoi usare JQuery per espandere textarea
durante la digitazione:
$(document).find('textarea').each(function () {
var offset = this.offsetHeight - this.clientHeight;
$(this).on('keyup input focus', function () {
$(this).css('height', 'auto').css('height', this.scrollHeight + offset);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea name="note"></textarea>
<div>
Alcune delle risposte qui non tengono conto del riempimento.
Supponendo che tu abbia un maxHeight su cui non vuoi andare oltre, questo ha funzionato per me:
// 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);
Un approccio ancora più semplice e più pulito è questo:
// 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();
// e il 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
}
Tutto ciò che serve è aggiungere la .auto-height
classe a qualsiasi textarea
che desideri scegliere come target.
Testato in FF, Chrome e Safari. Fammi sapere se questo non funziona per te, per qualsiasi motivo. Ma questo è il modo più semplice e pulito in cui ho trovato che funzionasse. E funziona benissimo! : D
Questo codice funziona per incollare e selezionare anche elimina.
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>
Ecco il JSFiddle
Usa <pre> </pre>
solo con alcuni stili come:
pre {
font-family: Arial, Helvetica, sans-serif;
white-space: pre-wrap;
word-wrap: break-word;
font-size: 12px;
line-height: 16px;
}
Coloro che vogliono ottenere lo stesso risultato nelle nuove versioni di Angular.
Prendi textArea elementRef.
@ViewChild('textArea', { read: ElementRef }) textArea: ElementRef;
public autoShrinkGrow() {
textArea.style.overflow = 'hidden';
textArea.style.height = '0px';
textArea.style.height = textArea.scrollHeight + 'px';
}
<textarea (keyup)="autoGrow()" #textArea></textarea>
Sto anche aggiungendo un altro caso d'uso che potrebbe tornare utile per alcuni utenti che leggono il thread, quando l'utente desidera aumentare l'altezza dell'area di testo a una certa altezza e quindi avere overflow:scroll
su di esso, il metodo sopra può essere esteso per raggiungere il caso d'uso menzionato.
public autoGrowShrinkToCertainHeight() {
const textArea = this.textArea.nativeElement;
if (textArea.scrollHeight > 77) {
textArea.style.overflow = 'auto';
return;
}
else {
textArea.style.overflow = 'hidden';
textArea.style.height = '0px';
textArea.style.height = textArea.scrollHeight + 'px';
}
}
Ecco cosa ho fatto usando MVC HTML Helper per TextArea. Ho avuto alcuni elementi textarea quindi ho dovuto distinguerli usando Model Id.
@Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })
e nello script ha aggiunto questo:
function resizeTextBox(ID) {
var text = document.getElementById('text' + ID);
text.style.height = 'auto';
text.style.height = text.scrollHeight + 'px';
}
L'ho provato su IE10 e Firefox23
Puoi usare questo codice:
CoffeeScript:
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();
Per coloro che desiderano ridimensionare automaticamente l'area di testo sia in larghezza che in altezza:
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
Saluti,
La soluzione jQuery è di impostare l'altezza della textarea su 'auto', controllare scrollHeight e quindi adattare l'altezza della textarea a quella, ogni volta che una textarea cambia ( JSFiddle ):
$('textarea').on( 'input', function(){
$(this).height( 'auto' ).height( this.scrollHeight );
});
Se stai aggiungendo dinamicamente textareas (tramite AJAX o altro), puoi aggiungerlo nel tuo $ (documento). Già per assicurarti che tutte le textareas con classe 'autoheight' siano mantenute alla stessa altezza del loro contenuto:
$(document).on( 'input', 'textarea.autoheight', function() {
$(this).height( 'auto' ).height( this.scrollHeight );
});
Testato e funzionante in Chrome, Firefox, Opera e IE. Supporta anche taglia e incolla, parole lunghe, ecc.
Puoi usare questo pezzo di codice per calcolare il numero di righe di cui una textarea ha bisogno:
textarea.rows = 1;
if (textarea.scrollHeight > textarea.clientHeight)
textarea.rows = textarea.scrollHeight / textarea.clientHeight;
Calcolalo su input
e window:resize
eventi per ottenere l'effetto di ridimensionamento automatico. Esempio in angolare:
Codice modello:
<textarea rows="1" reAutoWrap></textarea>
Auto-wrap.directive.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;
}
}
Soluzione Javascript nativa senza sfarfallio in Firefox e più veloce del metodo withclientHeight ...
1) Aggiungi div.textarea
selettore a tutti i selettori contenenti textarea
. Non dimenticare di aggiungere box-sizing: border-box;
2) Includi questo script:
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();
Testato su IE11, Firefox e Chrome.
Questa soluzione crea div simili alla tua textarea incluso testo interno e misura l'altezza.
Rendi Ridimensionabile TextArea che utilizza q Query
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();
}