回答編集履歴

1

TreeWalkerでの例を追加。

2017/11/29 07:51

投稿

x_x
x_x

スコア13749

test CHANGED
@@ -3,3 +3,103 @@
3
3
  そこで、幅を固定し、text-overflow: ellipsis を使うのはどうでしょうか?
4
4
 
5
5
  [https://developer.mozilla.org/ja/docs/Web/CSS/text-overflow](https://developer.mozilla.org/ja/docs/Web/CSS/text-overflow)
6
+
7
+
8
+
9
+ -- 追記。
10
+
11
+ ノード操作をした一例です。ちょっとうんざりしてくるのではないでしょうか?
12
+
13
+ ```JavaScript
14
+
15
+ function isHalf(code) {
16
+
17
+ return (code >= 0x0 && code < 0x81) || (code == 0xf8f0) || (code >= 0xff61 && code < 0xffa0) || (code >= 0xf8f1 && code < 0xf8f4);
18
+
19
+ }
20
+
21
+
22
+
23
+ function truncateTextNode(textNode) {
24
+
25
+ var text = textNode.nodeValue;
26
+
27
+ var newText = '';
28
+
29
+ for (var i = 0; i < text.length; i++) {
30
+
31
+ var c = text.charCodeAt(i);
32
+
33
+ var cost = isHalf(c) ? 0.5 : 1;
34
+
35
+ if (cost > remain) {
36
+
37
+ remain = -1;
38
+
39
+ textNode.nodeValue = newText;
40
+
41
+ return;
42
+
43
+ }
44
+
45
+
46
+
47
+ newText += text.charAt(i);
48
+
49
+ remain -= cost;
50
+
51
+ }
52
+
53
+
54
+
55
+ textNode.nodeValue = newText;
56
+
57
+ }
58
+
59
+
60
+
61
+ var remain = 50;
62
+
63
+ var root = document.querySelector('p.txt');
64
+
65
+ var tw = document.createTreeWalker(root);
66
+
67
+ var node;
68
+
69
+ while (node = tw.nextNode()) {
70
+
71
+ switch (node.nodeType) {
72
+
73
+ case document.ELEMENT_NODE:
74
+
75
+ if (remain < 0) {
76
+
77
+ node.setAttribute('data-remove', '1');
78
+
79
+ }
80
+
81
+
82
+
83
+ break;
84
+
85
+ case document.TEXT_NODE:
86
+
87
+ truncateTextNode(node);
88
+
89
+ break;
90
+
91
+ }
92
+
93
+ }
94
+
95
+
96
+
97
+ if (remain < 0) {
98
+
99
+ $(root.querySelectorAll('[data-remove]')).remove();
100
+
101
+ root.appendChild(document.createTextNode('…'));
102
+
103
+ }
104
+
105
+ ```