It was a hard fought battle, but I came up with a way to do this without any requirements for styles on the container at all (including its font, alignment, etc.).
This is not a perfect solution, but hopefully it works for your purposes.
var
//Keeps the content (individual spans) as they are built.
$keeper = $("<div>"),
//Used to measure span width for comparison to container.
$measurer = $("<div>"),
//The container of the text content
$p = $("p"),
//An individual line of the content
$line = $("<span>").appendTo($measurer),
//make this "invisible," but allow for measurement against container width
//with no restriction on measurer's own width (fixed)
$measurer.css({'position': 'fixed', 'top': '100%'}).appendTo("body");
//Iterate through each "word" derived from splitting on any space.
$p.text().split(/s/).forEach(function (elem) {
//Start forming line text. Don't forget word spacing
$line.text($line.text() + elem + ' ');
//Enough words to make the line width longer than the p width.
//This indicates the end of "line."
if ($line.width() > $p.width()) {
//Remove the last word.
$line.text(function (_, text) {
return text.slice(0, text.lastIndexOf(elem));
});
//Keep the currently formed line to add back later
$line.appendTo($keeper);
//Create a new line for measuring
$line = $("<span>");
$line.text(' ' + elem).appendTo($measurer);
}
});
//Append any leftover words not big enough to form a whole line
$keeper.append($measurer.html());
//Add back content
$p.html($keeper.html());
//cleanup
$keeper.remove();
$measurer.remove();
http://jsfiddle.net/6Cx3h/2/
You can also do this on window resize in case the container's width is window-dependent.
(you can see my attempt using height instead of width at http://jsfiddle.net/6Cx3h)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…