2009-11-19 10 views
21

Ho un elemento <textarea>. Posso usare JavaScript per rilevare che ci sono (per esempio) 10 righe di testo al suo interno?Come ottenere il numero di righe in <textarea > utilizzando JavaScript?

+0

Si potrebbe desiderare di chiarire la tua domanda in modo da non apparire come siete cercando di restituire l'attributo 'rows =' dall'elemento 'textarea'. –

+2

Perché dovresti farlo? Sento una cattiva specifica dei requisiti. – Randell

risposta

0

È possibile accedere al campo tramite DOM Javascript e contare semplicemente il numero di caratteri di nuova riga.

oArea = document.getElementById('myTextField'); 
var aNewlines = oArea.value.split("\n"); 
var iNewlineCount = aNewlines.length(); 
+3

Funzionerà solo per . Se il testo esegue il wrapping automatico, l'unico modo per farlo è usare un font a dimensione fissa, contare tutti i caratteri e quindi dividerli per i caratteri consentiti in una riga. E supponendo che non ci siano nuove righe nel processo ... \ n nessuno ?! – Frankie

+0

@ Frankie, giusto, ma come si calcola correttamente? – Mask

+0

È possibile disattivare il wrapping se questa è un'opzione che renderebbe il numero di newlines = numero di righe –

31

Bene, ho trovato un modo molto più semplice per farlo, ma è necessario impostare l'altezza della riga dell'area di testo nel CSS. Ho provato a leggere l'altezza della riga all'interno dello script ta.style.lineHeight ma non sembra che restituisca un valore.

CSS

#ta { width: 300px; line-height: 20px; } 

HTML

<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea> 

Script

var taLineHeight = 20; // This should match the line-height in the CSS 
var taHeight = ta.scrollHeight; // Get the scroll height of the textarea 
ta.style.height = taHeight; // This line is optional, I included it so you can more easily count the lines in an expanded textarea 
var numberOfLines = Math.floor(taHeight/taLineHeight); 
alert("there are " + numberOfLines + " lines in the text area"); 

Update: Grazie per @Pebbl per lavorare fuori gli insetti, questo è il codice necessario per ottenere l'altezza del contenuto del testo (demo)

var calculateContentHeight = function(ta, scanAmount) { 
    var origHeight = ta.style.height, 
     height = ta.offsetHeight, 
     scrollHeight = ta.scrollHeight, 
     overflow = ta.style.overflow; 
    /// only bother if the ta is bigger than content 
    if (height >= scrollHeight) { 
     /// check that our browser supports changing dimension 
     /// calculations mid-way through a function call... 
     ta.style.height = (height + scanAmount) + 'px'; 
     /// because the scrollbar can cause calculation problems 
     ta.style.overflow = 'hidden'; 
     /// by checking that scrollHeight has updated 
     if (scrollHeight < ta.scrollHeight) { 
      /// now try and scan the ta's height downwards 
      /// until scrollHeight becomes larger than height 
      while (ta.offsetHeight >= ta.scrollHeight) { 
       ta.style.height = (height -= scanAmount)+'px'; 
      } 
      /// be more specific to get the exact height 
      while (ta.offsetHeight < ta.scrollHeight) { 
       ta.style.height = (height++)+'px'; 
      } 
      /// reset the ta back to it's original height 
      ta.style.height = origHeight; 
      /// put the overflow back 
      ta.style.overflow = overflow; 
      return height; 
     } 
    } else { 
     return scrollHeight; 
    } 
} 

var calculateHeight = function() { 
    var ta = document.getElementById("ta"), 
     style = (window.getComputedStyle) ? 
      window.getComputedStyle(ta) : ta.currentStyle, 

     // This will get the line-height only if it is set in the css, 
     // otherwise it's "normal" 
     taLineHeight = parseInt(style.lineHeight, 10), 
     // Get the scroll height of the textarea 
     taHeight = calculateContentHeight(ta, taLineHeight), 
     // calculate the number of lines 
     numberOfLines = Math.ceil(taHeight/taLineHeight); 

    document.getElementById("lines").innerHTML = "there are " + 
     numberOfLines + " lines in the text area"; 
}; 

calculateHeight(); 
if (ta.addEventListener) { 
    ta.addEventListener("mouseup", calculateHeight, false); 
    ta.addEventListener("keyup", calculateHeight, false); 
} else if (ta.attachEvent) { // IE 
    ta.attachEvent("onmouseup", calculateHeight); 
    ta.attachEvent("onkeyup", calculateHeight); 
} 
+2

+1, questo è di gran lunga l'approccio più affidabile. Una nota: assicurati che la textarea inizi con 'rows = 1', altrimenti il ​​suo' scrollHeight' potrebbe essere artificialmente alto. –

+1

@Mottie l'oggetto '.style' restituirà sempre solo stili in linea. Per ottenere il valore calcolato dovresti usare 'window.getComputedStyle' e fallback su' Elm.currentStyle' per IE vecchio. Oltre a questo +1 :) – Pebbl

+1

Grazie per l'input @pebbl! Ho combinato i suggerimenti sopra riportati e realizzato [una demo] (http://jsfiddle.net/Mottie/PfD7L/). Si noti che quando ridimensionate manualmente l'area di testo nei browser moderni, il numero di linee cambierà per corrispondere all'altezza ridimensionata e non al contenuto. – Mottie

0
function countLines(area,maxlength) { 
     // var area = document.getElementById("texta") 
     // trim trailing return char if exists 
     var text = area.value.replace(/\s+$/g, "") 
     var split = text.split("\n") 
     if (split.length > maxlength) { 
      split = split.slice(0, maxlength); 
      area.value = split.join('\n'); 
      alert("You can not enter more than "+maxlength.toString()+" lines"); 
     } 
     return false; 
    } 

Questo è un semplice e testati uno

+3

Una newline non nota in modo definitivo l'interruzione di una riga. – Austin

+0

Certo che lo fa. Una rottura di una linea non significa tuttavia definitivamente una nuova riga. – dvlsg

2

linea Just uno js:

var rows = document.querySelector('textarea').value.split("\n").length; 
+0

Ho incontrato problemi con questo, a seconda del sistema operativo. In particolare la differenza tra \ r, \ r \ n, \ n \ r e \ n. Non ricordo esattamente perché, ma in realtà è stato abbastanza difficile farlo in modo esauriente in questo modo. – mike

+5

Cosa succede se ci sono più righe non a causa di caratteri di nuova riga ma perché una riga trabocca alla riga successiva? – brandaemon

Problemi correlati