Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
¿Detectando saltos de línea con jQuery?

¿Es posible que jQuery/javascript detecte dónde se rompe una cadena (para ajustarse a las restricciones de ancho de CSS) para insertar elementos DOM antes del comienzo de una nueva línea?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Se me ocurrió un enfoque, pero podría ser excesivo para sus propósitos, así que tenga esto en cuenta.

Debe crear un clon del elemento, vaciar el original y luego mover cada palabra de regreso al elemento original. Si la altura cambia en algún punto, hay un salto de línea antes de esa palabra. Esto sería bastante simple de hacer usando $(el).text() , pero se vuelve más complicado si puede haber otras etiquetas dentro, no solo texto. Traté de explicar cómo desglosarlo por nodo en este cuadro de respuesta, pero me resultó más fácil simplemente crear un complemento jQuery en un jsFiddle. Enlace aquí: http://jsfiddle.net/nathan/qkmse/ ( Gist ).

No manejará muy bien los elementos flotantes, y hay algunas otras situaciones en las que se caerá. Avíseme si desea más opciones, o si no funciona para sus propósitos, o si no está seguro de cómo aplicarlo, e intentaré ayudarlo.

over 4 years ago · Santiago Trujillo Report

0

Aquí hay un enfoque. Nota: no veo una solución ideal sin usar fuentes monoespaciadas. La igualdad con los personajes hace que esta tarea sea mucho más fácil.

  1. Caracteres de igual ancho
  2. Calcular el tamaño de un carácter
  3. Calcular el tamaño del contenedor.
  4. Buscar caracteres por fila
  5. Encuentre dónde se dividirá la fila (es decir, espacios en blanco, guiones, etc.)
  6. Obtenga todos los índices de ruptura.

Eche un vistazo al jsfiddle para el html asociado. No he completado esta función. Se deben realizar más comprobaciones al calcular el índice de ruptura. En este momento está usando lastIndexOf(' '), pero esto ignora que el siguiente índice podría ser un espacio o el actual. Además, no tengo en cuenta otros personajes que rompen líneas. Sin embargo, este debería ser un gran punto de partida.

 var text = $('#text').text(), // "lorem ipsum ... " len = text.length, // total chars width = $('#text').width(), // container width span = $('<span />').append('a').appendTo('#sandbox'), charWidth = span.width(), // add single character to span and test width charsPerRow = Math.floor(width/charWidth); // total characters that can fit in one row var breakingIndexes = [], // will contain indexes of all soft-breaks gRowStart = 0, // global row start index gRowEnd = charsPerRow;// global row end index while(gRowEnd < len){ var rowEnd = text.substring(gRowStart, gRowEnd).lastIndexOf(' '); // add more checks for break conditions here breakingIndexes.push(gRowStart + rowEnd); // add breaking index to array gRowStart = gRowStart + rowEnd + 1; // next start is the next char gRowEnd = gRowStart + charsPerRow; // global end inxex is start + charsperrow } var text2 = $('#text2').text(); // "lorem ipsum ... " now not width bound var start = 0, newText = ''; for(var i=0; i < breakingIndexes.length; i++){ newText += text2.substring(start, breakingIndexes[i]) + '<br />'; // add hard breaks start = breakingIndexes[i]; // update start } $('#text2').html(newText); // output with breaks

http://jsfiddle.net/Y5Ftn/1/

over 4 years ago · Santiago Trujillo Report

0

este es mi guión, que toma texto y luego hace que cada línea sea un lapso

CSS:

 margin: 0; padding: 0; } .title{ width: 300px; background-color: rgba(233,233,233,0.5); line-height: 20px; } span{ color: white; background-color: red; display: inline-block; font-size: 30px; } a{ text-decoration: none; color: black; }

html

 <div class="title"> <a href="">SOME TEXT LONG TEXT ANDTHISISLONG AND THIS OTHER TEXT</a> </div>

JS

 $(function(){ $(".title").find("a").each(function(){ var $this = $(this); var originalText = $this.text(); $this.empty(); var sections = []; $.each( originalText.split(" "), function(){ var $span = $("<span>" + this + "</span>"); $this.append($span); var index = $span.position().top; if( sections[index] === undefined ){ sections[index] = ""; } sections[index] += $span.text() + " "; }); $this.empty(); for(var i = 0; i< sections.length; i++){ if( sections[i] !== undefined ){ var spanText = $.trim(sections[i]); $this.append("<span>" + spanText + "</span>"); } } }); });

Tienes que incluir jQuery.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!