Skip to content

Commit 93e3230

Browse files
authored
Merge pull request #201 from xcurveballx/ru-2-3-3-mousemove-mouseover-mouseout-mouseenter-mouseleave
Ru 2 3 3 mousemove mouseover mouseout mouseenter mouseleave
2 parents b1818e0 + 1c31bc3 commit 93e3230

File tree

18 files changed

+290
-289
lines changed

18 files changed

+290
-289
lines changed

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<style>
77
body {
88
height: 2000px;
9-
/* the tooltip should work after page scroll too */
9+
/* подсказка должна работать и после прокрутки страницы */
1010
}
1111

1212
.tooltip {
@@ -49,41 +49,42 @@
4949
<body>
5050

5151

52-
<div data-tooltip="Here is the house interior" id="house">
53-
<div data-tooltip="Here is the roof" id="roof"></div>
52+
<div data-tooltip="Здесь домашний интерьер" id="house">
53+
<div data-tooltip="Здесь крыша" id="roof"></div>
5454

55-
<p>Once upon a time there was a mother pig who had three little pigs.</p>
55+
<p>Жили-были на свете три поросенка. Три брата. Все одинакового роста, кругленькие, розовые, с одинаковыми веселыми хвостиками.</p>
5656

57-
<p>The three little pigs grew so big that their mother said to them, "You are too big to live here any longer. You must go and build houses for yourselves. But take care that the wolf does not catch you."
57+
<p>Даже имена у них были похожи. Звали поросят: Ниф-Ниф, Нуф-Нуф и Наф-Наф. Все лето они кувыркались в зеленой траве, грелись на солнышке, нежились в лужах.</p>
5858

59-
<p>The three little pigs set off. "We will take care that the wolf does not catch us," they said.</p>
59+
<p>Но вот наступила осень. Солнце уже не так сильно припекало, серые облака тянулись над пожелтевшим лесом.</p>
6060

61-
<p>Soon they met a man. <a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a></p>
61+
<p>- Пора нам подумать о зиме, - сказал как-то Наф-Наф. <a href="https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B8_%D0%BF%D0%BE%D1%80%D0%BE%D1%81%D1%91%D0%BD%D0%BA%D0%B0" data-tooltip="Читать далее">Наведи курсор на меня</a></p>
6262

6363
</div>
6464

6565
<script>
6666
let tooltip;
6767

6868
document.onmouseover = function(event) {
69-
// important: a fast-moving mouse may "jump" right to a child on an annotated node, skipping the parent
70-
// so mouseover may happen on a child.
69+
// важно: быстро движущийся курсор может прыгнуть сразу к дочернему элементу, пропустив родительский
70+
// так что событие mouseover произойдёт сразу на дочернем элементе.
7171

7272
let anchorElem = event.target.closest('[data-tooltip]');
7373

7474
if (!anchorElem) return;
7575

76-
// show tooltip and remember it
76+
// показываем подсказку и запоминаем её
7777
tooltip = showTooltip(anchorElem, anchorElem.dataset.tooltip);
7878
}
7979

8080
document.onmouseout = function() {
81-
// it is possible that mouseout triggered, but we're still inside the element (cause of bubbling)
82-
// but in this case we'll have an immediate mouseover,
83-
// so the tooltip will be destroyed and shown again
81+
// возможно такое, что произошло событие mouseout, но мы всё ещё внутри элемента
82+
// (оно было где-то внутри и всплыло)
83+
// но в этом случае сразу же последует событие mouseover,
84+
// то есть подсказка исчезнет и потом снова покажется
8485
//
85-
// that's an overhead, but here it's not visible
86-
// can be fixed with additional checks
86+
// к счастью, этого не будет видно,
87+
// так как оба события происходят почти одновременно
8788
if (tooltip) {
8889
tooltip.remove();
8990
tooltip = false;
@@ -100,7 +101,7 @@
100101

101102
let coords = anchorElem.getBoundingClientRect();
102103

103-
// position the tooltip over the center of the element
104+
// позиционируем подсказку над центром элемента
104105
let left = coords.left + (anchorElem.offsetWidth - tooltipElem.offsetWidth) / 2;
105106
if (left < 0) left = 0;
106107

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<style>
77
body {
88
height: 2000px;
9-
/* the tooltip should work after page scroll too */
9+
/* подсказка должна работать и после прокрутки страницы */
1010
}
1111

1212
.tooltip {
@@ -49,21 +49,21 @@
4949
<body>
5050

5151

52-
<div data-tooltip="Here is the house interior" id="house">
53-
<div data-tooltip="Here is the roof" id="roof"></div>
52+
<div data-tooltip="Здесь домашний интерьер" id="house">
53+
<div data-tooltip="Здесь крыша" id="roof"></div>
5454

55-
<p>Once upon a time there was a mother pig who had three little pigs.</p>
55+
<p>Жили-были на свете три поросенка. Три брата. Все одинакового роста, кругленькие, розовые, с одинаковыми веселыми хвостиками.</p>
5656

57-
<p>The three little pigs grew so big that their mother said to them, "You are too big to live here any longer. You must go and build houses for yourselves. But take care that the wolf does not catch you."
57+
<p>Даже имена у них были похожи. Звали поросят: Ниф-Ниф, Нуф-Нуф и Наф-Наф. Все лето они кувыркались в зеленой траве, грелись на солнышке, нежились в лужах.</p>
5858

59-
<p>The three little pigs set off. "We will take care that the wolf does not catch us," they said.</p>
59+
<p>Но вот наступила осень. Солнце уже не так сильно припекало, серые облака тянулись над пожелтевшим лесом.</p>
6060

61-
<p>Soon they met a man. <a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a></p>
61+
<p>- Пора нам подумать о зиме, - сказал как-то Наф-Наф. <a href="https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B8_%D0%BF%D0%BE%D1%80%D0%BE%D1%81%D1%91%D0%BD%D0%BA%D0%B0" data-tooltip="Читать далее">Наведи курсор на меня</a></p>
6262

6363
</div>
6464

6565
<script>
66-
// ...your code...
66+
// ...ваш код...
6767
</script>
6868

6969
</body>

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/task.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@ importance: 5
22

33
---
44

5-
# Improved tooltip behavior
5+
# Улучшенная подсказка
66

7-
Write JavaScript that shows a tooltip over an element with the attribute `data-tooltip`.
7+
Напишите JavaScript код, который показывает подсказку над элементом со значением, взятым из атрибута `data-tooltip`.
88

9-
That's like the task <info:task/behavior-tooltip>, but here the annotated elements can be nested. The most deeply nested tooltip is shown.
9+
Это похоже на задачу <info:task/behavior-tooltip>, но здесь элементы с подсказками могут быть вложены друг в друга. Показываться должна подсказка на самом глубоко вложенном элементе.
1010

11-
For instance:
11+
Например:
1212

1313
```html
14-
<div data-tooltip="Here – is the house interior" id="house">
15-
<div data-tooltip="Here – is the roof" id="roof"></div>
14+
<div data-tooltip="Здесь - домашний интерьер" id="house">
15+
<div data-tooltip="Здесь - крыша" id="roof"></div>
1616
...
17-
<a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a>
17+
<a href="https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B8_%D0%BF%D0%BE%D1%80%D0%BE%D1%81%D1%91%D0%BD%D0%BA%D0%B0" data-tooltip="Читать далее">Наведи курсор на меня</a>
1818
</div>
1919
```
2020

21-
The result in iframe:
21+
Результат в iframe:
2222

2323
[iframe src="solution" height=300 border=1]
2424

25-
P.S. Hint: only one tooltip may show up at the same time.
25+
P.S. Подсказка: только одна подсказка может быть показана в любой момент времени.
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11

2-
The algorithm looks simple:
3-
1. Put `onmouseover/out` handlers on the element. Also can use `onmouseenter/leave` here, but they are less universal, won't work if we introduce delegation.
4-
2. When a mouse cursor entered the element, start measuring the speed on `mousemove`.
5-
3. If the speed is slow, then run `over`.
6-
4. Later if we're out of the element, and `over` was executed, run `out`.
2+
Алгоритм выглядит просто:
3+
1. Назначаем обработчики `onmouseover/out` на элементе. Также можно было бы использовать `onmouseenter/leave`, но они менее универсальны и не сработают с делегированием.
4+
2. Когда курсор переходит на элемент, начинаем измерять скорость его движения, используя `mousemove`.
5+
3. Если скорость низкая, то вызываем `over`.
6+
4. Позже, если мы уже не на элементе и `over` отработал, вызываем `out`.
77

8-
The question is: "How to measure the speed?"
8+
Вопрос: "Как измерить скорость?"
99

10-
The first idea would be: to run our function every `100ms` and measure the distance between previous and new coordinates. If it's small, then the speed is small.
10+
Первая приходящая в голову идея: запускать нашу функцию каждые `100ms` и находить разницу между прежними и текущими координатами курсора. Если она мала, то значит и скорость низкая.
1111

12-
Unfortunately, there's no way to get "current mouse coordinates" in JavaScript. There's no function like `getCurrentMouseCoordinates()`.
12+
К сожалению, в JavaScript нет возможности получать текущие координаты мыши. Не существует функции типа `getCurrentMouseCoordinates()`.
1313

14-
The only way to get coordinates is to listen to mouse events, like `mousemove`.
14+
Единственный путь - это подписаться и слушать события мыши, например `mousemove`.
1515

16-
So we can set a handler on `mousemove` to track coordinates and remember them. Then we can compare them, once per `100ms`.
16+
Таким образом, мы определяем обработчик на событие `mousemove`, чтобы отслеживать координаты и запоминать их. Затем мы можем сравнивать результаты каждые `100ms`.
1717

18-
P.S. Please note: the solution tests use `dispatchEvent` to see if the tooltip works right.
18+
P.S. Обратите внимание: тесты для решения этой задачи используют `dispatchEvent`, чтобы проверить, что подсказка работает корректно.

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/hoverIntent.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
class HoverIntent {
44

55
constructor({
6-
sensitivity = 0.1, // speed less than 0.1px/ms means "hovering over an element"
7-
interval = 100, // measure mouse speed once per 100ms
6+
sensitivity = 0.1, // скорость ниже 0.1px/ms значит "курсор на элементе"
7+
interval = 100, // измеряем скорость каждые 100ms
88
elem,
99
over,
1010
out
@@ -15,12 +15,12 @@ class HoverIntent {
1515
this.over = over;
1616
this.out = out;
1717

18-
// make sure "this" is the object in event handlers.
18+
// убедитесь, что "this" сохраняет своё значение для обработчиков.
1919
this.onMouseMove = this.onMouseMove.bind(this);
2020
this.onMouseOver = this.onMouseOver.bind(this);
2121
this.onMouseOut = this.onMouseOut.bind(this);
2222

23-
// and in time-measuring function (called from setInterval)
23+
// и в функции, измеряющей время (вызываемой из setInterval)
2424
this.trackSpeed = this.trackSpeed.bind(this);
2525

2626
elem.addEventListener("mouseover", this.onMouseOver);
@@ -32,16 +32,16 @@ class HoverIntent {
3232
onMouseOver(event) {
3333

3434
if (this.isOverElement) {
35-
// if we're over the element, then ignore the event
36-
// we are already measuring the speed
35+
// Игнорируем событие над элементом,
36+
// так как мы уже измеряем скорость
3737
return;
3838
}
3939

4040
this.isOverElement = true;
4141

42-
// after every mousemove we'll be check the distance
43-
// between the previous and the current mouse coordinates
44-
// if it's less than sensivity, then the speed is slow
42+
// после каждого движения измеряем дистанцию
43+
// между предыдущими и текущими координатами курсора
44+
// если скорость меньше sensivity, то она считается медленной
4545

4646
this.prevX = event.pageX;
4747
this.prevY = event.pageY;
@@ -52,13 +52,13 @@ class HoverIntent {
5252
}
5353

5454
onMouseOut(event) {
55-
// if left the element
55+
// если ушли с элемента
5656
if (!event.relatedTarget || !elem.contains(event.relatedTarget)) {
5757
this.isOverElement = false;
5858
this.elem.removeEventListener('mousemove', this.onMouseMove);
5959
clearInterval(this.checkSpeedInterval);
6060
if (this.isHover) {
61-
// if there was a stop over the element
61+
// если была остановка движения на элементе
6262
this.out.call(this.elem, event);
6363
this.isHover = false;
6464
}
@@ -76,7 +76,7 @@ class HoverIntent {
7676
let speed;
7777

7878
if (!this.lastTime || this.lastTime == this.prevTime) {
79-
// cursor didn't move
79+
// курсор не двигался
8080
speed = 0;
8181
} else {
8282
speed = Math.sqrt(
@@ -90,7 +90,7 @@ class HoverIntent {
9090
this.isHover = true;
9191
this.over.call(this.elem, event);
9292
} else {
93-
// speed fast, remember new coordinates as the previous ones
93+
// скорость высокая, запоминаем новые координаты
9494
this.prevX = this.lastX;
9595
this.prevY = this.lastY;
9696
this.prevTime = this.lastTime;

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
<span class="seconds">00</span>
1818
</div>
1919

20-
<div id="tooltip" hidden>Tooltip</div>
20+
<div id="tooltip" hidden>Подсказка</div>
2121

2222
<script>
23-
// for the demo
23+
// для демо
2424
setTimeout(function() {
2525
new HoverIntent({
2626
elem,

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/source.view/hoverIntent.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
'use strict';
22

3-
// Here's a brief sketch of the class
4-
// with things that you'll need anyway
3+
// Здесь показан набросок класса
4+
// с возможностями, которые нам понадобятся
55
class HoverIntent {
66

77
constructor({
8-
sensitivity = 0.1, // speed less than 0.1px/ms means "hovering over an element"
9-
interval = 100, // measure mouse speed once per 100ms: calculate the distance between previous and next points
8+
sensitivity = 0.1, // скорость ниже 0.1px/ms значит "курсор на элементе"
9+
interval = 100, // измеряем скорость каждые 100ms: определяем дистанцию между предыдущей и новой позицией.
1010
elem,
1111
over,
1212
out
@@ -17,16 +17,16 @@ class HoverIntent {
1717
this.over = over;
1818
this.out = out;
1919

20-
// make sure "this" is the object in event handlers.
20+
// убедитесь, что "this" сохраняет своё значение для обработчиков.
2121
this.onMouseMove = this.onMouseMove.bind(this);
2222
this.onMouseOver = this.onMouseOver.bind(this);
2323
this.onMouseOut = this.onMouseOut.bind(this);
2424

25-
// assign the handlers
25+
// назначаем обработчики
2626
elem.addEventListener("mouseover", this.onMouseOver);
2727
elem.addEventListener("mouseout", this.onMouseOut);
2828

29-
// continue from this point
29+
// продолжите с этого места
3030

3131
}
3232

@@ -44,7 +44,7 @@ class HoverIntent {
4444

4545

4646
destroy() {
47-
/* your code to "disable" the functionality, remove all handlers */
47+
/* ваш код для отключения функционала и снятия всех обработчиков */
4848
}
4949

5050
}

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/source.view/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<!doctype html>
2-
<html lang="en">
2+
<html>
33

44
<head>
55
<meta charset="UTF-8">
6-
<title>Document</title>
6+
<title>Документ</title>
77
<link rel="stylesheet" href="style.css">
88
<script src="hoverIntent.js"></script>
99
<script src="https://js.cx/test/libs.js"></script>
@@ -18,10 +18,10 @@
1818
<span class="seconds">00</span>
1919
</div>
2020

21-
<div id="tooltip" hidden>Tooltip</div>
21+
<div id="tooltip" hidden>Подсказка</div>
2222

2323
<script>
24-
// for the demo
24+
// для демо
2525
setTimeout(function() {
2626
new HoverIntent({
2727
elem,

0 commit comments

Comments
 (0)