You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/article.md
+48-48Lines changed: 48 additions & 48 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -99,73 +99,73 @@
99
99
```online
100
100
Ви можете це добре побачити в прикладі нижче: `<div id="child">` знаходиться всередині `<div id="parent">`. І обробники `mouseover/out` для елементу `#parent` виведуть деталі події.
101
101
102
-
If you move the mouse from `#parent` to `#child`, you see two events on `#parent`:
103
-
1. `mouseout [target: parent]` (left the parent), then
104
-
2. `mouseover [target: child]` (came to the child, bubbled).
102
+
Якщо ви перемістите вказівник миші від `#parent` до `#child`, це викличе дві події на `#parent`:
103
+
1. `mouseout [target: parent]` (вказівник залишив parent), далі
104
+
2. `mouseover [target: child]` (дійшов до child, спливання події).
105
105
106
106
[codetabs height=360 src="mouseoverout-child"]
107
107
```
108
108
109
-
As shown, when the pointer moves from`#parent`element to `#child`, two handlers trigger on the parent element: `mouseout`and`mouseover`:
109
+
Як показано, коли вказівник переміщується від елемента`#parent`до `#child`, на батьківському елементі запускаються два обробники: `mouseout`і`mouseover`:
110
110
111
111
```js
112
112
parent.onmouseout=function(event) {
113
-
/* event.target: parent element*/
113
+
/* event.target: parent елемент*/
114
114
};
115
115
parent.onmouseover=function(event) {
116
-
/* event.target: child element (bubbled) */
116
+
/* event.target: child елемент (спливання) */
117
117
};
118
118
```
119
119
120
-
**If we don't examine`event.target`inside the handlers, then it may seem that the mouse pointer left `#parent` element, and then immediately came back over it.**
120
+
**Якщо ми не перевіримо`event.target`всередині обробників, то може здатися, що вказівник миші залишив елемент `#parent`, а потім одразу повернувся на нього.**
121
121
122
-
But that's not the case! The pointer is still over the parent, it just moved deeper into the child element.
122
+
Але це не так! Вказівник все ще знаходиться над батьківським елементом, він просто перемістився глибше на дочірній елемент.
123
123
124
-
If there are some actions upon leaving the parent element, e.g. an animation runs in `parent.onmouseout`, we usually don't want it when the pointer just goes deeper into`#parent`.
124
+
Якщо є якісь дії після виходу з батьківського елемента, напр. анімація запускається в `parent.onmouseout`, ми зазвичай не хочемо цього, коли вказівник просто йде глибше в`#parent`.
125
125
126
-
To avoid it, we can check`relatedTarget`in the handler and, if the mouse is still inside the element, then ignore such event.
126
+
Щоб уникнути цього, ми можемо перевірити`relatedTarget`в обробнику і, якщо вказівник все ще всередині елемента, ігнорувати цю подію.
127
127
128
-
Alternatively we can use other events: `mouseenter`and`mouseleave`, that we'll be covering now, as they don't have such problems.
128
+
Як альтернативу ми можемо використовувати інші події: `mouseenter`і`mouseleave`, які ми зараз розглянемо, оскільки вони не мають таких проблем.
129
129
130
-
## Events mouseenter and mouseleave
130
+
## Події mouseenter і mouseleave
131
131
132
-
Events`mouseenter/mouseleave`are like`mouseover/mouseout`. They trigger when the mouse pointer enters/leaves the element.
132
+
Події`mouseenter/mouseleave`схожі на`mouseover/mouseout`. Вони спрацьовують, коли вказівник миші входить або залишає елемент.
133
133
134
-
But there are two important differences:
134
+
Але є дві важливі відмінності:
135
135
136
-
1.Transitions inside the element, to/from descendants, are not counted.
137
-
2.Events`mouseenter/mouseleave`do not bubble.
136
+
1.Переходи всередині елемента до/від нащадків не враховуються.
137
+
2.Події`mouseenter/mouseleave`не спливають.
138
138
139
-
These events are extremely simple.
139
+
Ці події надзвичайно прості.
140
140
141
-
When the pointer enters an element -- `mouseenter` triggers. The exact location of the pointer inside the element or its descendants doesn't matter.
141
+
Коли вказівник входить на елемент, спрацьовує `mouseenter`. Точне розташування вказівника всередині елемента або його нащадків не має значення.
142
142
143
-
When the pointer leaves an element -- `mouseleave` triggers.
143
+
Коли вказівник залишає елемент, спрацьовує `mouseleave`.
144
144
145
145
```online
146
-
This example is similar to the one above, but now the top element has `mouseenter/mouseleave` instead of `mouseover/mouseout`.
146
+
Цей приклад подібний до наведеного вище, але тепер у верхньому елементі є `mouseenter/mouseleave` замість `mouseover/mouseout`.
147
147
148
-
As you can see, the only generated events are the ones related to moving the pointer in and out of the top element. Nothing happens when the pointer goes to the child and back. Transitions between descendants are ignored
148
+
Як бачите, єдині генеровані події пов’язані з переміщенням вказівника в верхній елемент і з нього. Нічого не відбувається, коли покажчик йде до дочірнього елемента і назад. Переходи між нащадками ігноруються
149
149
150
150
[codetabs height=340 src="mouseleave"]
151
151
```
152
152
153
-
## Event delegation
153
+
## Делегування подій (Event delegation)
154
154
155
-
Events`mouseenter/leave`are very simple and easy to use. But they do not bubble. So we can't use event delegation with them.
155
+
Події`mouseenter/leave`дуже прості та легкі у використанні. Але вони не спливають. Тому ми не можемо використовувати з ними делегування подій (event delegation).
156
156
157
-
Imagine we want to handle mouse enter/leave for table cells. And there are hundreds of cells.
157
+
Уявіть, що ми хочемо керувати входом/виходом вказівника миші для клітинок таблиці, в якій сотні клітин.
158
158
159
-
The natural solution would be -- to set the handler on `<table>`and process events there. But`mouseenter/leave`don't bubble. So if such event happens on`<td>`, then only a handler on that `<td>`is able to catch it.
159
+
Ефективним рішенням було б встановити обробник на `<table>`і обробляти події там. Але`mouseenter/leave`не спливають. Отже, якщо така подія відбувається на`<td>`, то лише обробник на цьому `<td>`може її перехопити.
160
160
161
-
Handlers for`mouseenter/leave`on`<table>`only trigger when the pointer enters/leaves the table as a whole. It's impossible to get any information about transitions inside it.
161
+
Обробники для`mouseenter/leave`на`<table>`запускаються лише тоді, коли вказівник входить/виходить із таблиці в цілому. Інформацію про переходи всередині нього отримати неможливо.
162
162
163
-
So, let's use`mouseover/mouseout`.
163
+
Отже, давайте використаємо`mouseover/mouseout`.
164
164
165
-
Let's start with simple handlers that highlight the element under mouse:
165
+
Почнемо з простих обробників, які підсвічують елемент під вказіником миші:
In our case we'd like to handle transitions between table cells `<td>`: entering a cell and leaving it. Other transitions, such as inside the cell or outside of any cells, don't interest us. Let's filter them out.
186
+
У нашому випадку ми хочемо обробляти переходи між клітинами таблиці `<td>`: вхід у клітину та вихід з неї. Інші переходи, як всередині клітини або за її межами, нас не цікавлять. Відфільтруємо їх.
187
187
188
-
Here's what we can do:
188
+
Ось що ми можемо зробити:
189
189
190
-
-Remember the currently highlighted `<td>`in a variable, let's call it`currentElem`.
191
-
-On`mouseover` -- ignore the event if we're still inside the current`<td>`.
192
-
-On`mouseout` -- ignore if we didn't leave the current`<td>`.
1.It uses event delegation to handle entering/leaving of any `<td>`inside the table. So it relies on `mouseover/out`instead of `mouseenter/leave` that don't bubble and hence allow no delegation.
200
-
2.Extra events, such as moving between descendants of `<td>` are filtered out, so that `onEnter/Leave`runs only if the pointer leaves or enters`<td>` as a whole.
198
+
І ще раз про важливі особливості такого підходу:
199
+
1.Ми використовуємо делегування подій для обробки входу/виходу вказівника на будь-який `<td>`всередині таблиці. Таким чином, ми покладаємося на `mouseover/out`замість `mouseenter/leave`, які не спливають і, отже, не дозволяють делегування.
200
+
2.Додаткові події, такі як переміщення між нащадками `<td>`, відфільтровуються, тому `onEnter/Leave`запускається, лише якщо вказівник залишає або входить на`<td>`.
Try to move the cursor in and out of table cells and inside them. Fast or slow -- doesn't matter. Only `<td>` as a whole is highlighted, unlike the example before.
207
+
Спробуйте перемістити курсор у клітини таблиці та всередину них. Швидко чи повільно -- не має значення. На відміну від попереднього прикладу, виділено лише `<td>`.
208
208
```
209
209
210
-
## Summary
210
+
## Підсумки
211
211
212
-
We covered events`mouseover`, `mouseout`, `mousemove`, `mouseenter`and`mouseleave`.
212
+
Ми розглянули події`mouseover`, `mouseout`, `mousemove`, `mouseenter`і`mouseleave`.
213
213
214
-
These things are good to note:
214
+
Варто звернути увагу на такі речі:
215
215
216
-
-A fast mouse move may skip intermediate elements.
217
-
-Events`mouseover/out`and`mouseenter/leave`have an additional property: `relatedTarget`. That's the element that we are coming from/to, complementary to`target`.
216
+
-Швидкий рух миші може призвести до пропуску проміжних елементів.
217
+
-Події`mouseover/out`і`mouseenter/leave`мають додаткову властивість: `relatedTarget`. Це елемент, до/від якого ми йдемо, доповнюючи`target`.
218
218
219
-
Events`mouseover/out`trigger even when we go from the parent element to a child element. The browser assumes that the mouse can be only over one element at one time -- the deepest one.
219
+
Події`mouseover/out`запускаються, навіть коли ми переходимо від батьківського елемента до дочірнього. Браузер припускає, що вказівник миші може одночасно перебувати лише над одним елементом -- найглибшим.
220
220
221
-
Events`mouseenter/leave`are different in that aspect: they only trigger when the mouse comes in and out the element as a whole. Also they do not bubble.
221
+
Події`mouseenter/leave`відрізняються в цьому аспекті: вони запускаються лише тоді, коли вказівник миші входить і виходить з елемента в цілому. І ще вони не спливають.
0 commit comments