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
As it uses window coordinates, the element may be different depending on the current scroll position.
83
+
Поскольку используются координаты в контексте окна, то элемент может быть и другим в зависимости от того, имела ли место прокрутка.
84
84
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)`относятся к видимой части содержимого окна.
87
87
88
-
If any of the coordinates is negative or exceeds the window width/height, then it returns`null`.
88
+
Если любая из координат представляет собой отрицательное число или превышает размеры окна, то возвращается`null`.
89
89
90
-
In most cases such behavior is not a problem, but we should keep that in mind.
90
+
В большинстве случаев это не проблема, но всё же стоит держать сказанное в уме.
91
91
92
-
Here's a typical error that may occur if we don't check for it:
92
+
Вот типичная ошибка, которая может произойти, если в коде нет соответствующей проверки:
93
93
94
94
```js
95
95
let elem =document.elementFromPoint(x, y);
96
-
//if the coordinates happen to be out of the window, then elem = null
96
+
//если координаты ведут за пределы окна, то elem = null
97
97
*!*
98
-
elem.style.background=''; //Error!
98
+
elem.style.background=''; //Ошибка!
99
99
*/!*
100
100
```
101
101
````
102
102
103
-
## Using for position:fixed
103
+
## Координаты для position:fixed
104
104
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`).
106
106
107
-
We can use `getBoundingClientRect` to get coordinates of an element, and then to show something near it.
107
+
Мы можем вызвать `getBoundingClientRect`, чтобы получить координаты элемента, а затем показать что-то около него.
108
108
109
-
For instance, the function `createMessageUnder(elem, html)` below shows the message under `elem`:
109
+
Например, функция `createMessageUnder(elem, html)` ниже показывает сообщение под элементом `elem`:
110
110
111
111
```js
112
112
let elem = document.getElementById("coords-show-mark");
113
113
114
114
function createMessageUnder(elem, html) {
115
-
// create message element
115
+
// создаём элемент, который будет содержать сообщение
116
116
let message = document.createElement('div');
117
-
// better to use a css class for the style here
117
+
// для стилей лучше было бы использовать css-класс здесь
// устанавливаем координаты элементу, не забываем про "px"!
122
122
let coords = elem.getBoundingClientRect();
123
123
124
124
message.style.left = coords.left + "px";
@@ -130,28 +130,28 @@ function createMessageUnder(elem, html) {
130
130
return message;
131
131
}
132
132
133
-
// Usage:
134
-
// add it for 5 seconds in the document
133
+
// Использование:
134
+
// добавим сообщение на страницу на 5 секунд
135
135
let message = createMessageUnder(elem, 'Hello, world!');
136
136
document.body.append(message);
137
137
setTimeout(() => message.remove(), 5000);
138
138
```
139
139
140
140
```online
141
-
Click the button to run it:
141
+
Кликните кнопку, чтобы увидеть пример в действии:
142
142
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>
144
144
```
145
145
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-анимации и так далее. Это просто, так как в нашем распоряжении имеются все координаты и размеры элемента.
147
147
148
-
But note the important detail: when the page is scrolled, the message flows away from the button.
148
+
Но обратите внимание на одну важную деталь: при прокрутке страницы сообщение уплывает от кнопки.
149
149
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`, поэтому оно остаётся всегда на том же самом месте в окне при прокрутке страницы.
151
151
152
-
To change that, we need to use document-based coordinates and `position:absolute`.
152
+
Чтобы изменить это, нам нужно использовать другую систему координат, где сообщение позиционировалось бы относительно документа, и свойство `position:absolute`.
153
153
154
-
## Document coordinates
154
+
## Координаты в контексте документа
155
155
156
156
Document-relative coordinates start from the upper-left corner of the document, not the window.
0 commit comments