¿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?
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.
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.
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 breakseste 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.