回答編集履歴

2

修正

2019/04/09 11:39

投稿

退会済みユーザー
test CHANGED
@@ -170,7 +170,7 @@
170
170
 
171
171
 
172
172
 
173
- handleEvent () {
173
+ handleEvent (event) {
174
174
 
175
175
  if (event.target === this.target)
176
176
 

1

使いこなせるかどうかは別として、蛇足追加。

2019/04/09 11:38

投稿

退会済みユーザー
test CHANGED
@@ -47,3 +47,197 @@
47
47
 
48
48
 
49
49
  ```
50
+
51
+ 以下蛇足です。
52
+
53
+
54
+
55
+ さて、ここで問題です。途中で動作を止めたくなったら?そして再開したり、最初から表示させたくなったらどうするか?またそれらを独立して複数配置したくなったらどうするか?
56
+
57
+ ```javascript
58
+
59
+ <!DOCTYPE html>
60
+
61
+ <html lang="ja">
62
+
63
+ <meta charset="utf-8">
64
+
65
+ <title></title>
66
+
67
+
68
+
69
+ <body>
70
+
71
+ <ul>
72
+
73
+ <li>
74
+
75
+ <li>
76
+
77
+ <li>
78
+
79
+ <li>
80
+
81
+ <li>
82
+
83
+ </ul>
84
+
85
+
86
+
87
+
88
+
89
+ <script>
90
+
91
+
92
+
93
+ {
94
+
95
+ class Hoge {
96
+
97
+
98
+
99
+ constructor (target, text = '', wait = 100) {
100
+
101
+ this.target = target;
102
+
103
+ this.text = text;
104
+
105
+ this.wait = wait;
106
+
107
+ this.timerId = null;
108
+
109
+ this.ary = [ ];
110
+
111
+
112
+
113
+ this.clear ();
114
+
115
+ }
116
+
117
+
118
+
119
+ clear () {
120
+
121
+ this.target.textContent = '';
122
+
123
+ this.ary = this.text.split ('');
124
+
125
+ return this;
126
+
127
+ }
128
+
129
+
130
+
131
+ start () {
132
+
133
+ if (! this.timerId) {
134
+
135
+ if (! this.ary.length)
136
+
137
+ this.clear ();
138
+
139
+ this.timerId = setInterval (loop.bind (this), this.wait);
140
+
141
+ }
142
+
143
+ return this;
144
+
145
+ }
146
+
147
+
148
+
149
+ stop () {
150
+
151
+ if (this.timerId)
152
+
153
+ clearTimeout (this.timerId),
154
+
155
+ (this.timerId = null);
156
+
157
+ return this;
158
+
159
+ }
160
+
161
+
162
+
163
+ toggle () {
164
+
165
+ this.timerId ? this.stop (): this.start ();
166
+
167
+ return this;
168
+
169
+ }
170
+
171
+
172
+
173
+ handleEvent () {
174
+
175
+ if (event.target === this.target)
176
+
177
+ this.toggle ();
178
+
179
+ }
180
+
181
+
182
+
183
+ }
184
+
185
+
186
+
187
+ //____________________
188
+
189
+
190
+
191
+ const loop = function () {
192
+
193
+ (this.ary.length)
194
+
195
+ ? this.target.textContent += this.ary.shift ()
196
+
197
+ : this.stop ();
198
+
199
+ }
200
+
201
+
202
+
203
+ //____________________
204
+
205
+
206
+
207
+ this.Hoge = Hoge;
208
+
209
+
210
+
211
+ }
212
+
213
+
214
+
215
+ //__________
216
+
217
+
218
+
219
+ const str = 'この文字列をクリックすると一旦停止します。再開はもう一度クリックしてね';
220
+
221
+ const li = document.querySelectorAll ('li');
222
+
223
+
224
+
225
+ let cnt = 0;
226
+
227
+ for (let e of li) {
228
+
229
+ let obj = new Hoge (e, str, ++cnt * 100);
230
+
231
+ document.addEventListener ('click', obj, false);
232
+
233
+ obj.clear ().start ();
234
+
235
+ }
236
+
237
+
238
+
239
+ </script>
240
+
241
+
242
+
243
+ ```