Skip to content

Commit 0157530

Browse files
committed
часть 2
1 parent 2baea42 commit 0157530

File tree

1 file changed

+27
-27
lines changed

1 file changed

+27
-27
lines changed

2-ui/1-document/11-coordinates/article.md

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,15 @@ function showRect(elem) {
6060

6161
## elementFromPoint(x, y) [#elementFromPoint]
6262

63-
The call to `document.elementFromPoint(x, y)` returns the most nested element at window coordinates `(x, y)`.
63+
Вызов `document.elementFromPoint(x, y)` возвращает самый глубоко вложенный элемент в окне, находящийся по координатам `(x, y)`.
6464

65-
The syntax is:
65+
Синтаксис:
6666

6767
```js
6868
let elem = document.elementFromPoint(x, y);
6969
```
7070

71-
For instance, the code below highlights and outputs the tag of the element that is now in the middle of the window:
71+
Например, код ниже выделяет с помощью стилей и выводит имя тега элемента, который сейчас в центре окна браузера:
7272

7373
```js run
7474
let centerX = document.documentElement.clientWidth / 2;
@@ -80,45 +80,45 @@ elem.style.background = "red";
8080
alert(elem.tagName);
8181
```
8282

83-
As it uses window coordinates, the element may be different depending on the current scroll position.
83+
Поскольку используются координаты в контексте окна, то элемент может быть и другим в зависимости от того, имела ли место прокрутка.
8484

85-
````warn header="For out-of-window coordinates the `elementFromPoint` returns `null`"
86-
The method `document.elementFromPoint(x,y)` only works if `(x,y)` are inside the visible area.
85+
````warn header="Для координат за пределами окна метод `elementFromPoint` возвращает `null`"
86+
Метод `document.elementFromPoint(x,y)` работает, только если координаты `(x,y)` относятся к видимой части содержимого окна.
8787

88-
If any of the coordinates is negative or exceeds the window width/height, then it returns `null`.
88+
Если любая из координат представляет собой отрицательное число или превышает размеры окна, то возвращается `null`.
8989

90-
In most cases such behavior is not a problem, but we should keep that in mind.
90+
В большинстве случаев это не проблема, но всё же стоит держать сказанное в уме.
9191

92-
Here's a typical error that may occur if we don't check for it:
92+
Вот типичная ошибка, которая может произойти, если в коде нет соответствующей проверки:
9393

9494
```js
9595
let elem = document.elementFromPoint(x, y);
96-
// if the coordinates happen to be out of the window, then elem = null
96+
// если координаты ведут за пределы окна, то elem = null
9797
*!*
98-
elem.style.background = ''; // Error!
98+
elem.style.background = ''; // Ошибка!
9999
*/!*
100100
```
101101
````
102102
103-
## Using for position:fixed
103+
## Координаты для position:fixed
104104
105-
Most of time we need coordinates to position something. In CSS, to position an element relative to the viewport we use `position:fixed` together with `left/top` (or `right/bottom`).
105+
Чаще всего нам нужны координаты для позиционирования чего-либо. В CSS для позиционирования элемента относительно окна браузера используется свойство `position:fixed` вместе со свойствами `left/top` (или `right/bottom`).
106106
107-
We can use `getBoundingClientRect` to get coordinates of an element, and then to show something near it.
107+
Мы можем вызвать `getBoundingClientRect`, чтобы получить координаты элемента, а затем показать что-то около него.
108108
109-
For instance, the function `createMessageUnder(elem, html)` below shows the message under `elem`:
109+
Например, функция `createMessageUnder(elem, html)` ниже показывает сообщение под элементом `elem`:
110110
111111
```js
112112
let elem = document.getElementById("coords-show-mark");
113113
114114
function createMessageUnder(elem, html) {
115-
// create message element
115+
// создаём элемент, который будет содержать сообщение
116116
let message = document.createElement('div');
117-
// better to use a css class for the style here
117+
// для стилей лучше было бы использовать css-класс здесь
118118
message.style.cssText = "position:fixed; color: red";
119119
120120
*!*
121-
// assign coordinates, don't forget "px"!
121+
// устанавливаем координаты элементу, не забываем про "px"!
122122
let coords = elem.getBoundingClientRect();
123123
124124
message.style.left = coords.left + "px";
@@ -130,28 +130,28 @@ function createMessageUnder(elem, html) {
130130
return message;
131131
}
132132
133-
// Usage:
134-
// add it for 5 seconds in the document
133+
// Использование:
134+
// добавим сообщение на страницу на 5 секунд
135135
let message = createMessageUnder(elem, 'Hello, world!');
136136
document.body.append(message);
137137
setTimeout(() => message.remove(), 5000);
138138
```
139139
140140
```online
141-
Click the button to run it:
141+
Кликните кнопку, чтобы увидеть пример в действии:
142142
143-
<button id="coords-show-mark">Button with id="coords-show-mark", the message will appear under it</button>
143+
<button id="coords-show-mark">Кнопка с id="coords-show-mark", сообщение появится под ней</button>
144144
```
145145
146-
The code can be modified to show the message at the left, right, below, apply CSS animations to "fade it in" and so on. That's easy, as we have all the coordinates and sizes of the element.
146+
Код может быть изменён, чтобы показывать сообщение слева, справа, снизу, применять к нему CSS-анимации и так далее. Это просто, так как в нашем распоряжении имеются все координаты и размеры элемента.
147147
148-
But note the important detail: when the page is scrolled, the message flows away from the button.
148+
Но обратите внимание на одну важную деталь: при прокрутке страницы сообщение уплывает от кнопки.
149149
150-
The reason is obvious: the message element relies on `position:fixed`, so it remains at the same place of the window while the page scrolls away.
150+
Причина весьма очевидна: сообщение позиционируется с помощью `position:fixed`, поэтому оно остаётся всегда на том же самом месте в окне при прокрутке страницы.
151151
152-
To change that, we need to use document-based coordinates and `position:absolute`.
152+
Чтобы изменить это, нам нужно использовать другую систему координат, где сообщение позиционировалось бы относительно документа, и свойство `position:absolute`.
153153
154-
## Document coordinates
154+
## Координаты в контексте документа
155155
156156
Document-relative coordinates start from the upper-left corner of the document, not the window.
157157

0 commit comments

Comments
 (0)