diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.md b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.md index 28e8cffa97..8689458021 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.md +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.md @@ -1,4 +1,5 @@ +Как можно видеть из HTML/CSS, слайдер – это DIV, подкрашенный фоном/градиентом, внутри которого находится другой DIV, оформленный как бегунок, с position:relative. -We have a horizontal Drag'n'Drop here. +Бегунок немного поднят и вылезает по высоте из родителя. -To position the element we use `position:relative` and slider-relative coordinates for the thumb. Here it's more convenient here than `position:absolute`. +В этом случае мы реализуем горизонтальный Drag'n'Drop, ограниченный по ширине. Его особенность – в `position:relative` у переносимого элемента, т.е. координаты ставятся не абсолютные, а относительно родителя. diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.view/index.html b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.view/index.html index c364b42d9f..2646ce3bf4 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.view/index.html +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/solution.view/index.html @@ -16,10 +16,10 @@ let thumb = slider.querySelector('.thumb'); thumb.onmousedown = function(event) { - event.preventDefault(); // prevent selection start (browser action) + event.preventDefault(); // предотвратить запуск выделения (действие браузера) let shiftX = event.clientX - thumb.getBoundingClientRect().left; - // shiftY not needed, the thumb moves only horizontally + // shiftY здесь не нужен, слайдер двигается только по горизонтали document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); @@ -27,7 +27,7 @@ function onMouseMove(event) { let newLeft = event.clientX - shiftX - slider.getBoundingClientRect().left; - // the pointer is out of slider => lock the thumb within the bounaries + // курсор вышел из слайдера => оставить бегунок в его границах. if (newLeft < 0) { newLeft = 0; } diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/source.view/index.html b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/source.view/index.html index a9a545c09f..14f67e5323 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/source.view/index.html +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/source.view/index.html @@ -13,7 +13,7 @@ diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/task.md b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/task.md index 0c6da4e2c9..f084d792a1 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/task.md +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/1-slider/task.md @@ -2,15 +2,15 @@ importance: 5 --- -# Slider +# Слайдер -Create a slider: +Создайте слайдер: [iframe src="solution" height=60 border=1] -Drag the blue thumb with the mouse and move it. +Захватите мышкой синий бегунок и поперемещайте его. -Important details: +Важные детали: -- When the mouse button is pressed, during the dragging the mouse may go over or below the slider. The slider will still work (convenient for the user). -- If the mouse moves very fast to the left or to the right, the thumb should stop exactly at the edge. +- Слайдер должен нормально работать при резком движении мыши влево или вправо за пределы полосы. При этом бегунок должен останавливаться чётко в нужном конце полосы. +- При нажатом бегунке мышь может выходить за пределы полосы слайдера, но слайдер пусть все равно работает (это удобно для пользователя). diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.md b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.md index deb43b6551..c57f3bbcb6 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.md +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.md @@ -1,5 +1,5 @@ -To drag the element we can use `position:fixed`, it makes coordinates easier to manage. At the end we should switch it back to `position:absolute`. +Чтобы перетащить элемент, мы можем использовать `position:fixed`, это делает управление координатами проще. В конце следует переключиться обратно на `position:absolute`. -Then, when coordinates are at window top/bottom, we use `window.scrollTo` to scroll it. +Затем, когда координаты находятся в верхней/нижней части окна, мы используем его `window.scrollTo` для прокрутки. -More details in the code, in comments. +Детали решения расписаны в комментариях в исходном коде. diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/index.html b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/index.html index d79ef30a4e..6d147d1c39 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/index.html +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/index.html @@ -8,17 +8,17 @@ -

Place superheroes around the soccer field.

+

Расставьте супергероев по полю.

-

Superheroes and the ball are elements with the class "draggable". Make them really draggable.

+

Супергерои и мяч - это элементы с классом "draggable". Сделайте так, чтобы их можно было переносить.

+ +

Важно: ограничить перетаскивание границами окна. Если супергероя подносят к верхней или нижней границе страницы, она должна автоматически прокручиваться.

-

Important: limit dragging by the window. If a draggable reaches window top or bottom, then the page should scroll to let us drag it further.

+

Если страница помещается на вашем экране целиком и не имеет вертикальной прокрутки -- сделайте окно браузера меньше, чтобы протестировать эту возможность.

-

If your screen is big enough to fit the whole document -- make the window smaller to get vertical scrolling, so that you could test it.

+

В этой задаче достаточно справиться с вертикальной прокруткой. Обычно нет горизонтальной прокрутки, и она обрабатывается аналогичным образом, если это необходимо.

-

In this task it's enough to handle vertical scrolling. There's no horizontal scrolling usually, and it's handled the similar way if needed.

- -

And one more thing: heroes may never leave the page. If they reach the edge of the document, no dragging outside of it.

+

Да, и ещё: супергерои ни при каких условиях не должны попасть за край экрана.

diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/soccer.css b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/soccer.css index 00d5d70fc1..11a1af647b 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/soccer.css +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/solution.view/soccer.css @@ -10,7 +10,7 @@ html, body { float: left; } -/* heroes and the ball (dragables) */ +/* герои и мяч (переносимые элементы) */ .hero { background: url(https://js.cx/drag-heroes/heroes.png); diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/index.html b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/index.html index d79ef30a4e..6d147d1c39 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/index.html +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/index.html @@ -8,17 +8,17 @@ -

Place superheroes around the soccer field.

+

Расставьте супергероев по полю.

-

Superheroes and the ball are elements with the class "draggable". Make them really draggable.

+

Супергерои и мяч - это элементы с классом "draggable". Сделайте так, чтобы их можно было переносить.

+ +

Важно: ограничить перетаскивание границами окна. Если супергероя подносят к верхней или нижней границе страницы, она должна автоматически прокручиваться.

-

Important: limit dragging by the window. If a draggable reaches window top or bottom, then the page should scroll to let us drag it further.

+

Если страница помещается на вашем экране целиком и не имеет вертикальной прокрутки -- сделайте окно браузера меньше, чтобы протестировать эту возможность.

-

If your screen is big enough to fit the whole document -- make the window smaller to get vertical scrolling, so that you could test it.

+

В этой задаче достаточно справиться с вертикальной прокруткой. Обычно нет горизонтальной прокрутки, и она обрабатывается аналогичным образом, если это необходимо.

-

In this task it's enough to handle vertical scrolling. There's no horizontal scrolling usually, and it's handled the similar way if needed.

- -

And one more thing: heroes may never leave the page. If they reach the edge of the document, no dragging outside of it.

+

Да, и ещё: супергерои ни при каких условиях не должны попасть за край экрана.

diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.css b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.css index 00d5d70fc1..11a1af647b 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.css +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.css @@ -10,7 +10,7 @@ html, body { float: left; } -/* heroes and the ball (dragables) */ +/* герои и мяч (переносимые элементы) */ .hero { background: url(https://js.cx/drag-heroes/heroes.png); diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.js b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.js index ee04fda1c8..dbb290ee2e 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.js +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/source.view/soccer.js @@ -1 +1 @@ -// Your code +// ваш код diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/task.md b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/task.md index 16add0cf83..296858662b 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/task.md +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/2-drag-heroes/task.md @@ -2,19 +2,19 @@ importance: 5 --- -# Drag superheroes around the field +# Расставить супергероев по полю -This task can help you to check understanding of several aspects of Drag'n'Drop and DOM. +В этой задаче вы можете проверить своё понимание сразу нескольких аспектов Drag’n’Drop и DOM. -Make all elements with class `draggable` -- draggable. Like a ball in the chapter. +Сделайте так, чтобы элементы с классом `draggable` можно было переносить мышкой. Как мяч в этой главе. -Requirements: +Требования к реализации: -- Use event delegation to track drag start: a single event handler on `document` for `mousedown`. -- If elements are dragged to top/bottom window edges -- the page scrolls up/down to allow further dragging. -- There is no horizontal scroll. -- Draggable elements should never leave the window, even after swift mouse moves. +- Используйте делегирование событий для отслеживания начала перетаскивания: только один обработчик событий `mousedown` на документе. +- Если элементы подносят к верхней/нижней границе окна – оно должно прокручиваться вверх/вниз, чтобы позволить дальнейшее перетаскивание. +- Горизонтальной прокрутки в этой задаче не существует. +- Элемент при переносе, даже при резких движениях мышкой, не должен попасть вне окна. -The demo is too big to fit it here, so here's the link. +Демо слишком велико для размещения здесь, перейдите по ссылке ниже. [demo src="solution"] diff --git a/2-ui/3-event-details/4-mouse-drag-and-drop/article.md b/2-ui/3-event-details/4-mouse-drag-and-drop/article.md index 322dfe5f07..365c09b4b5 100644 --- a/2-ui/3-event-details/4-mouse-drag-and-drop/article.md +++ b/2-ui/3-event-details/4-mouse-drag-and-drop/article.md @@ -1,42 +1,42 @@ -# Drag'n'Drop with mouse events +# Drag'n'Drop с событиями мыши -Drag'n'Drop is a great interface solution. Taking something, dragging and dropping is a clear and simple way to do many things, from copying and moving (see file managers) to ordering (drop into cart). +Drag'n'Drop - отличный способ улучшить интерфейс. Захват элемента мышкой и его перенос визуально упростят что угодно: от копирования и перетаскивания в файловых менеджерах до оформления заказа в корзине. -In the modern HTML standard there's a [section about Drag and Drop](https://html.spec.whatwg.org/multipage/interaction.html#dnd) with special events such as `dragstart`, `dragend` and so on. +В современном стандарте HTML5 есть [раздел о Drag and Drop](https://html.spec.whatwg.org/multipage/interaction.html#dnd) - и там есть специальные события именно для Drag'n'Drop переноса, такие как `dragstart`, `dragend` и так далее. -They are interesting because they allow to solve simple tasks easily, and also allow to handle drag'n'drop of "external" files into the browser. So we can take a file in the OS file-manager and drop it into the browser window. Then JavaScript gains access to its contents. +Они интересны тем, что позволяют легко решать простые задачи. Например, можно перетащить файл в браузер, так что JS получит доступ к его содержимому. -But native Drag Events also have limitations. For instance, we can't limit dragging by a certain area. Also we can't make it "horizontal" or "vertical" only. There are other drag'n'drop tasks that can't be implemented using that API. +Но у них есть и ограничения. Например, нельзя организовать перенос "только по горизонтали" или "только по вертикали". Также нельзя ограничить перенос внутри заданной зоны. Есть и другие интерфейсные задачи, которые такими встроенными событиями не реализуемы. -So here we'll see how to implement Drag'n'Drop using mouse events. Not that hard either. +Поэтому здесь мы будем рассматривать Drag’n’Drop при помощи событий мыши. Это не так уж сложно. -## Drag'n'Drop algorithm +## Алгоритм Drag'n'Drop -The basic Drag'n'Drop algorithm looks like this: +Основной алгоритм Drag’n’Drop выглядит так: -1. Catch `mousedown` on a draggable element. -2. Prepare the element for moving (maybe create a copy of it or whatever). -3. Then on `mousemove` move it by changing `left/top` and `position:absolute`. -4. On `mouseup` (button release) -- perform all actions related to a finished Drag'n'Drop. +1. Отслеживаем событие `mousedown` на переносимом элементе. +2. При нажатии – готовим элемент к перемещению (например, создаём его копию). +3. При наступлении `mousemove` передвигаем элемент на новые координаты путём смены `left/top` и `position:absolute`. +4. На `mouseup` (при отпускании кнопки мыши) -- остановить перенос элемента и произвести все действия, связанные с окончанием Drag’n’Drop.. -These are the basics. We can extend it, for instance, by highlighting droppable (available for the drop) elements when hovering over them. +Это и есть база Drag'n'Drop. Мы могли бы расширить этот алгоритм, например, подсветив элементы при наведении на них курсора. -Here's the algorithm for drag'n'drop of a ball: +В следующем примере эти шаги реализованы для переноса мяча: ```js -ball.onmousedown = function(event) { // (1) start the process +ball.onmousedown = function(event) { // (1) отследить нажатие - // (2) prepare to moving: make absolute and on top by z-index + // (2) подготовить к перемещению: разместить поверх остального содержимого и в абсолютных координатах ball.style.position = 'absolute'; ball.style.zIndex = 1000; - // move it out of any current parents directly into body - // to make it positioned relative to the body + // переместим в body, чтобы мяч был точно не внутри position:relative document.body.append(ball); - // ...and put that absolutely positioned ball under the cursor + // и установим абсолютно спозиционированный мяч под курсор moveAt(event.pageX, event.pageY); - // centers the ball at (pageX, pageY) coordinates + // передвинуть мяч под координаты курсора + // и сдвинуть на половину ширины/высоты для центрирования function moveAt(pageX, pageY) { ball.style.left = pageX - ball.offsetWidth / 2 + 'px'; ball.style.top = pageY - ball.offsetHeight / 2 + 'px'; @@ -46,10 +46,10 @@ ball.onmousedown = function(event) { // (1) start the process moveAt(event.pageX, event.pageY); } - // (3) move the ball on mousemove + // (3) перемещать по экрану document.addEventListener('mousemove', onMouseMove); - // (4) drop the ball, remove unneeded handlers + // (4) положить мяч, удалить более ненужные обработчики событий ball.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); ball.onmouseup = null; @@ -58,19 +58,19 @@ ball.onmousedown = function(event) { // (1) start the process }; ``` -If we run the code, we can notice something strange. On the beginning of the drag'n'drop, the ball "forks": we start dragging its "clone". +Если запустить этот код, то мы заметим нечто странное. При начале переноса мяч "раздваивается" и переносится не сам мяч, а его "клон". ```online -Here's an example in action: +Это можно увидеть в действии: [iframe src="ball" height=230] -Try to drag'n'drop the mouse and you'll see the strange behavior. +Попробуйте перенести мяч мышкой и вы увидите описанное, довольно-таки странное, поведение. ``` -That's because the browser has its own Drag'n'Drop for images and some other elements that runs automatically and conflicts with ours. +Всё потому, что браузер имеет свой собственный Drag’n’Drop, который автоматически запускается и вступает в конфликт с нашим. Это происходит именно для картинок и некоторых других элементов. -To disable it: +Его нужно отключить: ```js ball.ondragstart = function() { @@ -78,40 +78,40 @@ ball.ondragstart = function() { }; ``` -Now everything will be all right. +Теперь всё будет в порядке. ```online -In action: +В действии: [iframe src="ball2" height=230] ``` -Another important aspect -- we track `mousemove` on `document`, not on `ball`. From the first sight it may seem that the mouse is always over the ball, and we can put `mousemove` on it. +Ещё одна особенность правильного Drag’n’Drop -- событие `mousemove` отслеживается на `document`, а не на `ball`. С первого взгляда кажется, что мышь всегда над мячом и обработчик `mousemove` можно повесить на сам мяч, а не на документ. -But as we remember, `mousemove` triggers often, but not for every pixel. So after swift move the cursor can jump from the ball somewhere in the middle of document (or even outside of the window). +Но как мы помним, событие `mousemove` возникает хоть и часто, но не для каждого пикселя. Поэтому из-за быстрого движения курсор может спрыгнуть с мяча и оказаться где-нибудь в середине документа (или даже за пределами окна). -So we should listen on `document` to catch it. +Вот почему мы должны отслеживать `mousemove` на всём `document`, чтобы поймать его. -## Correct positioning +## Правильное позиционирование -In the examples above the ball is always moved so, that it's center is under the pointer: +В примерах выше мяч позиционируется так, что его центр оказывается под курсором мыши: ```js ball.style.left = pageX - ball.offsetWidth / 2 + 'px'; ball.style.top = pageY - ball.offsetHeight / 2 + 'px'; ``` -Not bad, but there's a side-effect. To initiate the drag'n'drop, we can `mousedown` anywhere on the ball. But if do it at the edge, then the ball suddenly "jumps" to become centered. +Неплохо, но есть побочные эффекты. В частности, в самом начале переноса, особенно если мячик "взят" за край – он резко "прыгает" центром под курсор мыши. -It would be better if we keep the initial shift of the element relative to the pointer. +Было бы лучше, если бы изначальный сдвиг курсора относительно элемента сохранялся. -For instance, if we start dragging by the edge of the ball, then the cursor should remain over the edge while dragging. +Где захватили, за ту "часть элемента" и переносим: ![](ball_shift.png) -1. When a visitor presses the button (`mousedown`) -- we can remember the distance from the cursor to the left-upper corner of the ball in variables `shiftX/shiftY`. We should keep that distance while dragging. +1. Когда человек нажимает на мячик (`mousedown`) -- мы можем зафиксировать расстояние от курсора до левого верхнего угла шара в переменных `shiftX/shiftY`. И нужно удерживать это расстояние при перетаскивании. - To get these shifts we can substract the coordinates: + Чтобы получить этот сдвиг, мы можем вычесть координаты: ```js // onmousedown @@ -119,7 +119,7 @@ For instance, if we start dragging by the edge of the ball, then the cursor shou let shiftY = event.clientY - ball.getBoundingClientRect().top; ``` -2. Then while dragging we position the ball on the same shift relative to the pointer, like this: +2. Далее при переносе мяча мы позиционируем его с тем же сдвигом относительно указателя мыши, вот так: ```js // onmousemove @@ -128,7 +128,7 @@ For instance, if we start dragging by the edge of the ball, then the cursor shou ball.style.top = event.pageY - *!*shiftY*/!* + 'px'; ``` -The final code with better positioning: +Итоговый код с правильным позиционированием: ```js ball.onmousedown = function(event) { @@ -144,8 +144,8 @@ ball.onmousedown = function(event) { moveAt(event.pageX, event.pageY); - // moves the ball at (pageX, pageY) coordinates - // taking initial shifts into account + // переносит мяч на координаты (pageX, pageY), + // дополнительно учитывая изначальный сдвиг относительно указателя мыши function moveAt(pageX, pageY) { ball.style.left = pageX - *!*shiftX*/!* + 'px'; ball.style.top = pageY - *!*shiftY*/!* + 'px'; @@ -155,10 +155,10 @@ ball.onmousedown = function(event) { moveAt(event.pageX, event.pageY); } - // move the ball on mousemove + // передвигаем мяч при событии mousemove document.addEventListener('mousemove', onMouseMove); - // drop the ball, remove unneeded handlers + // отпустить мяч, удалить ненужные обработчики ball.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); ball.onmouseup = null; @@ -172,30 +172,30 @@ ball.ondragstart = function() { ``` ```online -In action (inside `