Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
Javascript: cómo contar caracteres para cada línea de un div

Estoy diseñando mi sitio web y tengo problemas con la tipografía. Me gustaría darme cuenta de cuántos caracteres hay en cada línea de mi párrafo div. ¿Hay alguna forma de hacer esto con Javascript o jQuery?

Por ejemplo: tengo un div de 720 px de ancho con un tamaño de fuente de 18 px, ¿cómo puedo contar cuántos caracteres hay para cada línea? Si esto es factible, también me gustaría entender cómo contar los espacios o excluirlos del conteo.

Actualmente estoy usando $("#mydiv p").text().length pero cuenta todos los caracteres y no los caracteres de cada línea.

Agradezco cualquier ayuda y gracias por cualquier respuesta.

 document.write( $("#mydiv p").text().length );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="mydiv" style="font-size: 18px; width: 720px; border: 1px solid red;"> <p>This is my div! This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!</p> </div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Si solo necesita establecer un límite de caracteres por línea, simplemente use la unidad ch así:

 .max720{ width:720px; font-size:18px; } .max50ch p{ max-width:50ch; }
 <div class="max720 max50ch"> <p><strong>Max 50 characters per line.</strong> One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p> <p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p> </div>

Ejemplo 2: contar caracteres por línea

Si necesita obtener el recuento exacto de caracteres por línea, deberá dividir el contenido de su texto en una matriz de caracteres y verificar el offsetHeight de la línea.

 let paragraphs = document.querySelectorAll("p"); paragraphs.forEach(function (paragraph, p) { let text = paragraph.textContent; //split to character array let textArr = text.split(""); //append temporary span element let line = document.createElement("span"); paragraph.insertBefore(line, paragraph.firstChild); let charCount = 0; let charArr = []; let lineNo = 1; let lineY = line.offsetHeight; textArr.forEach(function (char, i) { //add text character by character line.textContent += char; charCount++; let currentY = line.offsetHeight; //currentY > lineY = new line if (currentY > lineY || i == textArr.length - 1) { let charPerLine = charCount - 1; console.log(`paragraph ${p+1}; line ${lineNo}: ${charPerLine} characters`); lineY = currentY; charCount = 0; lineNo++; } }); //remove span line.remove(); });
 .max720{ width:720px; font-size:18px; }
 <div class="max720 max72ch"> <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p> <p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p> </div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda