Can I use the browser's word-wrapping from JavaScript?

此生再无相见时 提交于 2020-01-12 09:45:08

问题


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?


回答1:


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/ ).



来源:https://stackoverflow.com/questions/3050378/can-i-use-the-browsers-word-wrapping-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!