问题
I'm looking for a way to use jQuery to do what I can do in php with wordwrap() (http://php.net/manual/en/function.wordwrap.php)
I would use php but I need the wrapping to happen dynamically after the dom is loaded--
I am not familiar enough with jQuery to write this sort of function from scratch and I have run a few google and stack searches trying to find a premade plugin or something that's done it already.
Any ideas? Or perhaps a starting place?
Thanks!
EDIT:
for clarification I need to be able to add html at the line breaks (</p><p>
, for example)--
as php :
wordwrap($text, 8, "</p><p>", true);
回答1:
http://james.padolsey.com/javascript/wordwrap-for-javascript/
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
回答2:
There appears to be a word wrap plugin for jQuery which is a cross browser solution for word wrapping a textarea
. If you are not looking to use this on a textarea
you could try setting the width of the <p>
tag so that it wraps the text.
Something like
<p style="width:50%">some text that is way longer than this</p>
回答3:
You can do it directly with CSS:
.break-word {
word-wrap: break-word;
}
Word-wrap is supported in IE 5.5+, Firefox 3.5+, and WebKit browsers such as Chrome and Safari.
http://webdesignerwall.com/tutorials/word-wrap-force-text-to-wrap
来源:https://stackoverflow.com/questions/8423994/jquery-equivalent-of-phps-wordwrap