2009-11-19 62 views
21

Tengo un elemento <textarea>. ¿Puedo usar JavaScript para detectar que hay (por ejemplo) 10 filas de texto en él?¿Cómo obtener el número de filas en <textarea > usando JavaScript?

+0

Es posible que desee para aclarar su pregunta por lo que no se ve como si estuviera tratando de devolver el atributo 'rows =' del elemento 'textarea'. –

+2

¿Por qué querrías hacer esto? Siento una especificación de requisito malo. – Randell

Respuesta

0

Puede acceder al campo a través de Javascript DOM y simplemente contar el número de caracteres de nueva línea.

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

Esto solo funcionará para . Si el texto se ajusta automáticamente, la única manera de hacerlo es usar una fuente de tamaño fijo, contar todos los caracteres y luego dividirlos por los caracteres permitidos en una fila. Y eso suponiendo que no haya nuevas líneas en el proceso ... \ n ¿alguien? – Frankie

+0

@ Frankie, ¿correcto, pero cómo calcularlo correctamente? – Mask

+0

Puede desactivar el envoltorio si esa es una opción que haría que el número de líneas nuevas = número de filas –

31

Bueno he encontrado una manera más simple tanto para hacer esto, pero usted tendrá que establecer la línea de altura de la caja de texto en la CSS. Traté de leer la altura de la línea dentro del script ta.style.lineHeight pero no parece devolver un valor.

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> 

Guión

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"); 

Actualización: Gracias a @Pebbl para la elaboración de los insectos, este es el código necesario para conseguir el alto del contenido del texto (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, este es de lejos el enfoque más confiable. Una nota: asegúrese de que el área de texto comience con 'rows = 1', o su' scrollHeight' puede ser artificialmente alto. –

+1

@Mottie el objeto '.style' solo devolverá estilos en línea. Para obtener el valor calculado, debe usar 'window.getComputedStyle' y recurrir a' Elm.currentStyle' para IE antiguo. Aparte de eso +1 :) – Pebbl

+1

Gracias por la entrada @pebbl! Combiné las sugerencias anteriores e hice [una demostración] (http://jsfiddle.net/Mottie/PfD7L/). Tenga en cuenta que cuando cambie manualmente el tamaño del área de texto en los navegadores modernos, la cantidad de líneas cambiará para coincidir con la altura ajustada y no con el contenido. – 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; 
    } 

esta es una forma sencilla y probada uno

+3

Una nueva línea no indica definitivamente el quiebre de una línea. – Austin

+0

Claro que sí. Sin embargo, una ruptura de una línea no significa definitivamente una nueva línea. – dvlsg

2

línea Solo una JS:

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

He tenido problemas con este, dependiendo del sistema operativo. En particular, la diferencia entre \ r, \ r \ n, \ n \ r, y \ n. No recuerdo exactamente por qué, pero en realidad fue bastante difícil hacerlo exhaustivamente de esta manera. – mike

+5

¿Qué sucede si hay varias líneas no debido a caracteres de nueva línea sino porque una línea se desborda a la línea siguiente? – brandaemon

Cuestiones relacionadas