teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

訂正

2020/09/27 06:28

投稿

AkitoshiManabe
AkitoshiManabe

スコア5434

answer CHANGED
@@ -34,12 +34,13 @@
34
34
  }
35
35
 
36
36
  _splitText( txt ) {
37
+ // 返却値 : undefined から innerHTML に訂正
37
- if( !txt || this.textsplit ) return;
38
+ if( !txt || this.textsplit ) return this.el.innerHTML;
38
- this.textsplit = true;
39
+ this.textsplit = true;
39
- return txt.trim().split("").reduce((acc, curr) => {
40
+ return txt.trim().split("").reduce((acc, curr) => {
40
- curr = curr.replace(/\s+/, ' ');
41
+ curr = curr.replace(/\s+/, ' ');
41
- return `${acc}<span class="char">${curr}</span>`;
42
+ return `${acc}<span class="char">${curr}</span>`;
42
- }, "");
43
+ }, "");
43
44
  }
44
45
 
45
46
  animate() {

1

追記

2020/09/27 06:28

投稿

AkitoshiManabe
AkitoshiManabe

スコア5434

answer CHANGED
@@ -15,4 +15,43 @@
15
15
 
16
16
  > (3つの div.animate-title が)それぞれ画面内に入ったときに、アニメーションを開始するよう実装
17
17
 
18
- * 現在の``TextAnimation`` の実装では不可能です。改修してください。
18
+ * 現在の``TextAnimation`` の実装では不可能です。改修してください。
19
+
20
+ ----
21
+ 追記)
22
+
23
+ TextAnimation オブジェクトはアニメーションさせたい1つの要素に紐付ける形をとると判りやすいのではないでしょうか。
24
+
25
+ ```javascript
26
+ class TextAnimation {
27
+ constructor(el) {
28
+ if( !el instanceof HTMLElement ) {
29
+ throw TypeError("required HTMLElement in a argument");
30
+ }
31
+ this.textsplit = false; // 分割済みかどうか
32
+ this.el = el;
33
+ el.innerHTML = this._splitText( el.textContent );
34
+ }
35
+
36
+ _splitText( txt ) {
37
+ if( !txt || this.textsplit ) return;
38
+ this.textsplit = true;
39
+ return txt.trim().split("").reduce((acc, curr) => {
40
+ curr = curr.replace(/\s+/, '&nbsp;');
41
+ return `${acc}<span class="char">${curr}</span>`;
42
+ }, "");
43
+ }
44
+
45
+ animate() {
46
+ // 分割されている場合にアニメーション用スタイル '.inview' を適用する
47
+ if( this.textsplit )
48
+ this.el.classList.add('inview');
49
+ }
50
+ }
51
+
52
+ document.querySelectorAll(".animate-title").forEach( el => {
53
+ let anim = new TextAnimation(el);
54
+ console.log( anim.el === el );
55
+ /* omitted */
56
+ });
57
+ ```