-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
97 lines (79 loc) · 2.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function TextSplitr(elt, options) {
this.chars = [];
this.words = [];
this.options = options;
this.options = {
type: 'chars'
};
if(options) {
for (var attrname in options) { this.options[attrname] = options[attrname]; }
}
var html = elt.innerHTML;
var typeChars = this.options.type.indexOf('chars') >= 0;
var typeWords = this.options.type.indexOf('words') >= 0;
var tags = [];
var found = html.match(/<span[^>]*>(.*?)<\/span>/g);
for(var i=0; i<found.length; i++) {
var pos = html.indexOf(found[i]);
tags[pos] = found[i];
}
elt.innerHTML = '';
var i=0;
var lastSpace = true, word=null;
while(i < html.length) {
if(tags[i]) {
var strTag = tags[i];
i += strTag.length;
//elt.appendChild(this.createCharContainer(tag));
elt.insertAdjacentHTML("beforeEnd", strTag);
var tag = elt.childNodes[elt.childNodes.length-1];
this.words.push(tag);
this.chars.push(tag);
} else {
var c = html.charAt(i);
var isSpace = (c == ' ');
if(typeChars && !typeWords) {
if(isSpace) {
elt.appendChild(document.createTextNode(' '));
} else {
elt.appendChild(this.createCharContainer(c));
}
}
if(typeWords) {
if(isSpace) {
elt.appendChild(document.createTextNode(' '));
lastSpace = true;
} else {
if (lastSpace) {
lastSpace = false;
word = this.createWordContainer('');
elt.appendChild(word);
}
if(typeChars) {
word.appendChild(this.createCharContainer(c));
} else {
word.innerHTML += c;
}
}
}
i++;
}
}
}
TextSplitr.prototype.createCharContainer = function(html) {
var div = document.createElement('div');
div.style.display = 'inline-block';
div.style.position = 'relative';
div.innerHTML = html;
this.chars.push(div);
return div;
};
TextSplitr.prototype.createWordContainer = function(html) {
var div = document.createElement('div');
div.style.display = 'inline-block';
div.style.position = 'relative';
div.innerHTML = html;
this.words.push(div);
return div;
};
exports = TextSplitr;