Home >Web Front-end >JS Tutorial >JavaScript supports line wrapping of page text_javascript skills
I encountered a problem, that is, when the page is displayed, in many cases it is necessary to wrap the displayed text, for example, the text exceeds the width of TD, or the width of DIV, etc.
There is word-break and so on under IE, but it does not work under FF, so I did some research and wrote a JS script. The principle is as follows:
1. First, we put it on the page Find a span element, use it to load characters, and then use its width to get the display width of the character
2. Then, when we display a string, we can use the character width obtained previously to calculate The width of each string
3. On this basis, it is not a problem to calculate the position where the string should be broken, and insert
to break the line.
Due to limited conditions, blog cannot upload attachments. I will explain the code here.
The code has two parts, one is "textWidth.js", which does most of the work; the other is the test page.
1. textWidth.js
Source code | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
var TextWidth = new function() { var widthLib = new Hash(); var textSpan; var self = this; |
|
||||||||||||||||||
Calculate the length of the string. The algorithm is simple, just add the width of each character together. The key is getSizeLib(fontName, fontSize); this function, if there is no width data for this font size in the Hash table, it will actively initialize the corresponding width data | |||||||||||||||||||
Calculates line breaks. This is also simple. First get the width data from the Hash table, and then calculate it one by one. If the width exceeds, add in |
|||||||||||||||||||
Save the span element used for width calculation | |||||||||||||||||||
Gets the width data of the specified font size. If not, initialize one | |||||||||||||||||||
Initialization | |||||||||||||||||||