收录日期:2019/04/26 16:19:52 时间:2010-06-16 02:45:21 标签:javascript,browser,word-wrap

I have some text in a div. It can be any Unicode text under the sun, including Chinese, Japanese, and Korean. Now, I need to take this text and word-wrap it in JavaScript in some efficient but correct manner. Then I need to insert a ">" at the start of every line, and put the resulting text into a textarea.

Browsers have an implementation of the Unicode Word Wrap algorithm, as is evidenced by word-wrapping Unicode text in a with CSS. (At least, Firefox has such an algorithm, and I suspect other browsers do as well.) What I need is some way for JavaScript to use the same word-wrapping algorithm, so that I can properly wrap and then "quote" Unicode text.

Is there any way for JavaScript to use the browser's word-wrapping algorithm, or to know where text has been line-broken in a div or any other element?

What you really want isn't necessarily to insert ">" in the flowed text at the beginning of every line. What you really want is for every line in a given block to have a ">" at the left of it.

You could potentially do the latter by:

1) Creating an image of the ">" character, with its height from top to bottom equivalent to the CSS line-height value you plan on using. Apply that image as a background on the container of the text you want this "inserted" into. Have it repeat vertically, but not horizontally. Pad the container the width of the character/image.

2) Have some javascript get the computed value of the line-height property for the container you're working with. Then, assuming you're not artificially setting the height of this container, the number of "lines" of text in the container is its offsetHeight divided by the computed line-height. At this point, create a separate container that has nothing but that number of >'s as its content. Position it to the left edge of your content container.

Your larger question about whether you have access to the text-flow algorithm the browser uses via JavaScript is an interesting one, but I'm pretty sure the answer is no. However, as more developers start playing with the Canvas element, people are writing their own (Canvas has text drawing, but not its own flow-layout algorithm for text). You might want to see what the Bespin guys did (https://bespin.mozillalabs.com/ - it's a text editor implemented using the Canvas) or check out the source of some of the sandbag/image textwrapping javascript libraries like jQSlickWrap (http://jwf.us/projects/jQSlickWrap/ ).