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/1-document/11-coordinates/article.md
+33-33Lines changed: 33 additions & 33 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,38 +1,38 @@
1
-
# Coordinates
1
+
# Координаты
2
2
3
-
To move elements around we should be familiar with coordinates.
3
+
Чтобы передвигать элементы по экрану, нам следует познакомиться с системами координат.
4
4
5
-
Most JavaScript methods deal with one of two coordinate systems:
5
+
Большинство соответствующих методов JavaScript работают в одной из двух указанных ниже систем координат:
6
6
7
-
1.Relative to the window(or another viewport) top/left.
8
-
2.Relative to the document top/left.
7
+
1.Относительно верхнего левого угла окна браузера (или его видимой части).
8
+
2.Относительно верхнего левого угла документа.
9
9
10
-
It's important to understand the difference and which type is where.
10
+
Важно понимать разницу между этими системами, а также где какая используется.
11
11
12
-
## Window coordinates: getBoundingClientRect
12
+
## Координаты относительно окна: getBoundingClientRect
13
13
14
-
Window coordinates start at the upper-left corner of the window.
14
+
Начальной точкой служит верхний левый угол окна браузера.
15
15
16
-
The method `elem.getBoundingClientRect()`returns window coordinates for `elem`as an object with properties:
16
+
Метод `elem.getBoundingClientRect()`возвращает координаты в контексте окна для элемента `elem`в виде объекта со свойствами:
17
17
18
-
-`top` -- Y-coordinate for the top element edge,
19
-
-`left` -- X-coordinate for the left element edge,
20
-
-`right` -- X-coordinate for the right element edge,
21
-
-`bottom` -- Y-coordinate for the bottom element edge.
18
+
-`top` -- позиция по оси Y верхнего края элемента,
19
+
-`left` -- позиция по оси X левого края элемента,
20
+
-`right` -- позиция по оси X правого края элемента,
21
+
-`bottom` -- позиция по оси Y нижнего края элемента.
22
22
23
-
Like this:
23
+
Вот так:
24
24
25
25

26
26
27
27
28
-
Window coordinates do not take the scrolled out part of the document into account, they are calculated from the window's upper-left corner.
28
+
Координаты относительно окна не учитывают прокрутку, они считаются от левого верхнего угла.
29
29
30
-
In other words, when we scroll the page, the element goes up or down, *its window coordinates change*. That's very important.
30
+
Другими словами, если мы прокрутим страницу, и элемент уйдёт вниз или вверх, то это *изменит его координаты в контексте окна*. Это очень важно.
31
31
32
32
```online
33
-
Click the button to see its window coordinates:
33
+
Кликните на кнопку, чтобы увидеть её координаты относительно окна:
34
34
35
-
<input id="brTest" type="button" value="Show button.getBoundingClientRect() for this button" onclick='showRect(this)'/>
35
+
<input id="brTest" type="button" value="Показать результат вызова button.getBoundingClientRect() для этой кнопки" onclick='showRect(this)'/>
36
36
37
37
<script>
38
38
function showRect(elem) {
@@ -41,21 +41,21 @@ function showRect(elem) {
41
41
}
42
42
</script>
43
43
44
-
If you scroll the page, the button position changes, and window coordinates as well.
44
+
Если вы прокрутите страницу, то позиция кнопки поменяется, и её координаты в контексте окна тоже.
45
45
```
46
46
47
-
Also:
47
+
Также:
48
48
49
-
-Coordinates may be decimal fractions. That's normal, internally browser uses them for calculations. We don't have to round them when setting to`style.position.left/top`, the browser is fine with fractions.
50
-
-Coordinates may be negative. For instance, if the page is scrolled down and the top `elem`is now above the window. Then,`elem.getBoundingClientRect().top`is negative.
51
-
-Some browsers (like Chrome) provide additional properties,`width`and`height`of the element that invoked the method to `getBoundingClientRect` as the result. We can also get them by subtraction: `height=bottom-top`, `width=right-left`.
49
+
-Координаты могут считаться с десятичной дробью. Это нормально, ведь браузер использует дроби в своих внутренних вычислениях. Мы не обязаны округлять значения при установке`style.position.left/top`, браузер прекрасно понимает координаты с десятичными дробями.
50
+
-Координаты могут быть отрицательными. Например, если страница прокручена вниз и верхняя часть элемента `elem`ушла за пределы окна, то вызов`elem.getBoundingClientRect().top`вернёт отрицательное значение.
51
+
-Некоторые браузеры (типа Chrome) предоставляют дополнительные свойства`width`и`height`элемента, для которого вызывалась функция `getBoundingClientRect`. Их можно также получить путём вычитания: `height=bottom-top`, `width=right-left`.
52
52
53
-
```warn header="Coordinates right/bottom are different from CSS properties"
54
-
If we compare window coordinates versus CSS positioning, then there are obvious similarities to `position:fixed`. The positioning of an element is also relative to the viewport.
53
+
```warn header="Координаты right/bottom отличаются от одноимённых CSS-свойств"
54
+
Если мы сравним координаты в контексте окна и координаты при позиционировании средствами CSS, то мы увидим сходство при использовании `position:fixed`. Ведь такое CSS-позиционирование тоже происходит относительно окна браузера (или его видимой части).
55
55
56
-
But in CSS, the `right` property means the distance from the right edge, and the `bottom` property means the distance from the bottom edge.
56
+
Но в CSS свойство `right` означает расстояние от правого края, и свойство `bottom` означает расстояние от нижнего края окна браузера.
57
57
58
-
If we just look at the picture above, we can see that in JavaScript it is not so. All window coordinates are counted from the upper-left corner, including these ones.
58
+
Если мы взглянем на картинку выше, то будет понятно, что в JavaScript это не так. Все координаты в контексте окна считаются от верхнего левого угла, включая `right/bottom`.
59
59
```
60
60
61
61
## elementFromPoint(x, y) [#elementFromPoint]
@@ -197,13 +197,13 @@ function getCoords(elem) {
197
197
}
198
198
```
199
199
200
-
## Summary
200
+
## Итого
201
201
202
-
Any point on the page has coordinates:
202
+
Любая точка на странице имеет координаты:
203
203
204
-
1. Relative to the window -- `elem.getBoundingClientRect()`.
205
-
2. Relative to the document -- `elem.getBoundingClientRect()` plus the current page scroll.
204
+
1. Относительно окна браузера -- `elem.getBoundingClientRect()`.
205
+
2. Относительно документа -- `elem.getBoundingClientRect()` плюс прокрутка.
206
206
207
-
Window coordinates are great to use with `position:fixed`, and document coordinates do well with `position:absolute`.
207
+
Координаты в контексте окна подходят для использования с `position:fixed`, а координаты относительно документа -- для использования с `position:absolute`.
208
208
209
-
Both coordinate systems have their "pro" and "contra", there are times we need one or the other one, just like CSS `position` `absolute` and `fixed`.
209
+
Каждая из систем координат имеет свои преимущества и недостатки. Иногда будет лучше применить одну, а иногда -- другую, как это и происходит с позиционированием в CSS, где мы выбираем между `absolute` и `fixed`.
0 commit comments