回答編集履歴

2

修正版

2017/05/19 05:08

投稿

yambejp
yambejp

スコア114581

test CHANGED
@@ -113,3 +113,55 @@
113
113
  </div>
114
114
 
115
115
  ```
116
+
117
+
118
+
119
+ # 修正版
120
+
121
+ ```ここに言語を入力
122
+
123
+ var timerId=[];
124
+
125
+ window.onload=function(){
126
+
127
+ var hoge=document.querySelectorAll('.hoge');
128
+
129
+ for(var i=0;i<hoge.length;i++){
130
+
131
+ hoge[i].setAttribute("data-hoge",i);
132
+
133
+ }
134
+
135
+ }
136
+
137
+ document.addEventListener("mouseover",function(e){myFunc(e)});
138
+
139
+ document.addEventListener("mouseout",function(e){myFunc(e)});
140
+
141
+ function myFunc(e){
142
+
143
+ var t=e.target;
144
+
145
+ if(num=t.getAttribute("data-hoge")){
146
+
147
+ if(e.type=="mouseover"){
148
+
149
+ timerId[num]=setTimeout(function(){
150
+
151
+ t.style.backgroundColor="red";
152
+
153
+ },3000);
154
+
155
+ }
156
+
157
+ if(e.type=="mouseout"){
158
+
159
+ clearTimeout(timerId[num]);
160
+
161
+ }
162
+
163
+ }
164
+
165
+ }
166
+
167
+ ```

1

追記

2017/05/19 05:08

投稿

yambejp
yambejp

スコア114581

test CHANGED
@@ -37,3 +37,79 @@
37
37
  </div>
38
38
 
39
39
  ```
40
+
41
+
42
+
43
+ # 追記
44
+
45
+ 複数のsetTimeoutを管理する場合、timerIdを配列してもてばよいでしょう
46
+
47
+
48
+
49
+ ```javascript
50
+
51
+ var timerId=[];
52
+
53
+ document.addEventListener("mouseover",function(e){myFunc(e)});
54
+
55
+ document.addEventListener("mouseout",function(e){myFunc(e)});
56
+
57
+ function myFunc(e){
58
+
59
+ var t=e.target;
60
+
61
+ var hoge=document.querySelectorAll('.hoge');
62
+
63
+ for(var i=0;i<hoge.length;i++){
64
+
65
+ if(t==hoge[i]){
66
+
67
+ if(e.type=="mouseover"){
68
+
69
+ timerId[i]=setTimeout(function(){
70
+
71
+ t.style.backgroundColor="red";
72
+
73
+ },3000);
74
+
75
+ }
76
+
77
+ if(e.type=="mouseout"){
78
+
79
+ clearTimeout(timerId[i]);
80
+
81
+ }
82
+
83
+ }
84
+
85
+ }
86
+
87
+ }
88
+
89
+
90
+
91
+ ```
92
+
93
+
94
+
95
+ ```HTML
96
+
97
+ <div class="hoge" style="background-Color:lime;">
98
+
99
+ マウスをのせた3秒後に赤になる
100
+
101
+ </div>
102
+
103
+ <div class="hoge" style="background-Color:aqua;">
104
+
105
+ マウスをのせた3秒後に赤になる
106
+
107
+ </div>
108
+
109
+ <div class="hoge" style="background-Color:yellow;">
110
+
111
+ マウスをのせた3秒後に赤になる
112
+
113
+ </div>
114
+
115
+ ```