JavaScript supports line wrapping of page text_javascript skills
WBOY
Release: 2016-05-16 18:51:32
Original
1717 people have browsed it
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;
Copy after login
源代码
说明
self.getWidth = function(string, fontName, fontSize) {
var lib = getSizeLib(fontName, fontSize);
var totalWidth = 0;
for(var i =0; i < string.length; i++) {
var c = string.charCodeAt(i);
if (c > 255) {
totalWidth += lib[256];
}else{
totalWidth += lib[c];
}
}
return totalWidth;
}
Copy after login
内部成员变量
widthLib是一个保存某个字体、字号的所有字符的宽度的hash表;
self.wrapText = function(string, fontName, fontSize, maxWidth) {
if (!string) {
return " ";
}
var origText = string.strip();
var lib = getSizeLib(fontName, fontSize);
var resultText = "";
var deltaW;
var totalW = 0;
for(var i =0; i < string.length; i++) {
var c = string.charCodeAt(i);
if (c > 255) {
deltaW = lib[256];
}else{
deltaW = lib[c];
}
if ((totalW + deltaW) > maxWidth)
{
resultText += "";
totalW = deltaW;
}else{
totalW += deltaW;
}
resultText += string.charAt(i);
}
return resultText;
}
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
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn