Skip to content

Commit 2baea42

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

File tree

1 file changed

+33
-33
lines changed

1 file changed

+33
-33
lines changed

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

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
# Coordinates
1+
# Координаты
22

3-
To move elements around we should be familiar with coordinates.
3+
Чтобы передвигать элементы по экрану, нам следует познакомиться с системами координат.
44

5-
Most JavaScript methods deal with one of two coordinate systems:
5+
Большинство соответствующих методов JavaScript работают в одной из двух указанных ниже систем координат:
66

7-
1. Relative to the window(or another viewport) top/left.
8-
2. Relative to the document top/left.
7+
1. Относительно верхнего левого угла окна браузера (или его видимой части).
8+
2. Относительно верхнего левого угла документа.
99

10-
It's important to understand the difference and which type is where.
10+
Важно понимать разницу между этими системами, а также где какая используется.
1111

12-
## Window coordinates: getBoundingClientRect
12+
## Координаты относительно окна: getBoundingClientRect
1313

14-
Window coordinates start at the upper-left corner of the window.
14+
Начальной точкой служит верхний левый угол окна браузера.
1515

16-
The method `elem.getBoundingClientRect()` returns window coordinates for `elem` as an object with properties:
16+
Метод `elem.getBoundingClientRect()` возвращает координаты в контексте окна для элемента `elem` в виде объекта со свойствами:
1717

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 нижнего края элемента.
2222

23-
Like this:
23+
Вот так:
2424

2525
![](coords.png)
2626

2727

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+
Координаты относительно окна не учитывают прокрутку, они считаются от левого верхнего угла.
2929

30-
In other words, when we scroll the page, the element goes up or down, *its window coordinates change*. That's very important.
30+
Другими словами, если мы прокрутим страницу, и элемент уйдёт вниз или вверх, то это *изменит его координаты в контексте окна*. Это очень важно.
3131

3232
```online
33-
Click the button to see its window coordinates:
33+
Кликните на кнопку, чтобы увидеть её координаты относительно окна:
3434
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)'/>
3636
3737
<script>
3838
function showRect(elem) {
@@ -41,21 +41,21 @@ function showRect(elem) {
4141
}
4242
</script>
4343
44-
If you scroll the page, the button position changes, and window coordinates as well.
44+
Если вы прокрутите страницу, то позиция кнопки поменяется, и её координаты в контексте окна тоже.
4545
```
4646

47-
Also:
47+
Также:
4848

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`.
5252

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-позиционирование тоже происходит относительно окна браузера (или его видимой части).
5555
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` означает расстояние от нижнего края окна браузера.
5757
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`.
5959
```
6060

6161
## elementFromPoint(x, y) [#elementFromPoint]
@@ -197,13 +197,13 @@ function getCoords(elem) {
197197
}
198198
```
199199
200-
## Summary
200+
## Итого
201201
202-
Any point on the page has coordinates:
202+
Любая точка на странице имеет координаты:
203203
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()` плюс прокрутка.
206206
207-
Window coordinates are great to use with `position:fixed`, and document coordinates do well with `position:absolute`.
207+
Координаты в контексте окна подходят для использования с `position:fixed`, а координаты относительно документа -- для использования с `position:absolute`.
208208
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

Comments
 (0)