Skip to content

Commit 630e482

Browse files
authored
Window sizes and scrolling (#279)
1 parent c696797 commit 630e482

File tree

1 file changed

+69
-69
lines changed
  • 2-ui/1-document/10-size-and-scroll-window

1 file changed

+69
-69
lines changed
Lines changed: 69 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,50 @@
1-
# Window sizes and scrolling
1+
# Розміри вікна і прокрутка
22

3-
How do we find the width and height of the browser window? How do we get the full width and height of the document, including the scrolled out part? How do we scroll the page using JavaScript?
3+
Як визначити ширину та висоту вікна браузера? Як отримати повну ширину та висоту документа, включаючи прокручену частину? Як можна прокрутити сторінку за допомогою JavaScript?
44

5-
For this type of information, we can use the root document element `document.documentElement`, that corresponds to the `<html>` tag. But there are additional methods and peculiarities to consider.
5+
Для цього ми можемо використовувати кореневий елемент документа `document.documentElement`, який відповідає тегу `<html>`. Але є додаткові методи та особливості, які слід враховувати.
66

7-
## Width/height of the window
7+
## Ширина/висота вікна
88

9-
To get window width and height, we can use the `clientWidth/clientHeight` of `document.documentElement`:
9+
Щоб отримати ширину та висоту вікна, ми можемо використовувати `clientWidth/clientHeight` із `document.documentElement`:
1010

1111
![](document-client-width-height.svg)
1212

1313
```online
14-
For instance, this button shows the height of your window:
14+
Наприклад, ця кнопка показує висоту вашого вікна:
1515
1616
<button onclick="alert(document.documentElement.clientHeight)">alert(document.documentElement.clientHeight)</button>
1717
```
1818

19-
````warn header="Not `window.innerWidth/innerHeight`"
20-
Browsers also support properties like `window.innerWidth/innerHeight`. They look like what we want, so why not to use them instead?
19+
````warn header="Не `window.innerWidth/innerHeight`"
20+
Браузери також підтримують властивості `window.innerWidth/innerHeight`. Здається, це те, що нам потрібно, то чому б їх не використати?
2121

22-
If there exists a scrollbar, and it occupies some space, `clientWidth/clientHeight` provide the width/height without it (subtract it). In other words, they return the width/height of the visible part of the document, available for the content.
22+
Якщо є смуга прокрутки, і вона займає деякий простір, то властивості `clientWidth/clientHeight` нададуть ширину/висоту без прокрутки (віднявши її). Інакше кажучи, вони повертають ширину/висоту видимої частини документа, доступної для вмісту.
2323

24-
`window.innerWidth/innerHeight` includes the scrollbar.
24+
`window.innerWidth/innerHeight` включає смугу прокрутки.
2525

26-
If there's a scrollbar, and it occupies some space, then these two lines show different values:
26+
Якщо є смуга прокрутки, і вона займає деякий простір, то ці два рядки покажуть різні значення:
2727
```js run
28-
alert( window.innerWidth ); // full window width
29-
alert( document.documentElement.clientWidth ); // window width minus the scrollbar
28+
alert( window.innerWidth ); // повна ширина вікна
29+
alert( document.documentElement.clientWidth ); // ширина вікна мінус смуга прокрутки
3030
```
3131

32-
In most cases, we need the *available* window width in order to draw or position something within scrollbars (if there are any), so we should use `documentElement.clientHeight/clientWidth`.
32+
У більшості випадків нам потрібна *доступна* ширина вікна, щоб намалювати або розташувати щось у межах смуг прокрутки (якщо такі є), тому ми повинні використовувати `documentElement.clientHeight/clientWidth`.
3333
````
3434
35-
```warn header="`DOCTYPE` is important"
36-
Please note: top-level geometry properties may work a little bit differently when there's no `<!DOCTYPE HTML>` in HTML. Odd things are possible.
35+
```warn header="`DOCTYPE` важливий"
36+
Зверніть увагу: геометричні властивості верхнього рівня можуть працювати дещо інакше, якщо в HTML немає `<!DOCTYPE HTML>`. Можливі дивні речі.
3737
38-
In modern HTML we should always write `DOCTYPE`.
38+
У сучасному HTML ми завжди повинні прописувати `DOCTYPE`.
3939
```
4040
41-
## Width/height of the document
41+
## Ширина/висота документа
4242
43-
Theoretically, as the root document element is `document.documentElement`, and it encloses all the content, we could measure the document's full size as `document.documentElement.scrollWidth/scrollHeight`.
43+
Теоретично, оскільки кореневим елементом документа є `document.documentElement`, і він охоплює весь вміст, ми можемо виміряти повний розмір документа як `document.documentElement.scrollWidth/scrollHeight`.
4444
45-
But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera, if there's no scroll, then `documentElement.scrollHeight` may be even less than `documentElement.clientHeight`! Weird, right?
45+
Але для цього елемента для всієї сторінки ці властивості не працюють належним чином. У Chrome/Safari/Opera, якщо немає прокрутки, то `documentElement.scrollHeight` може бути навіть меншим, ніж `documentElement.clientHeight`! Дивно, правда?
4646
47-
To reliably obtain the full document height, we should take the maximum of these properties:
47+
Щоб надійно отримати повну висоту документа, ми повинні взяти максимум з цих властивостей:
4848
4949
```js run
5050
let scrollHeight = Math.max(
@@ -53,110 +53,110 @@ let scrollHeight = Math.max(
5353
document.body.clientHeight, document.documentElement.clientHeight
5454
);
5555
56-
alert('Full document height, with scrolled out part: ' + scrollHeight);
56+
alert('Повна висота документа з прокрученою частиною: ' + scrollHeight);
5757
```
5858
59-
Why so? Better don't ask. These inconsistencies come from ancient times, not a "smart" logic.
59+
Чому так? Краще не питати. Ці невідповідності походять із давніх часів, це не "логічно".
6060
61-
## Get the current scroll [#page-scroll]
61+
## Отримання поточної позиції прокрутки [#page-scroll]
6262
63-
DOM elements have their current scroll state in their `scrollLeft/scrollTop` properties.
63+
Елементи DOM містять свій поточний стан прокрутки у властивостях `scrollLeft/scrollTop`.
6464
65-
For document scroll, `document.documentElement.scrollLeft/scrollTop` works in most browsers, except older WebKit-based ones, like Safari (bug [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), where we should use `document.body` instead of `document.documentElement`.
65+
Стан прокрутки документа міститься в `document.documentElement.scrollLeft/scrollTop`, та працює в більшості браузерів, за винятком старіших веб-переглядачів створених на WebKit, таких як Safari (помилка [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), де ми повинні використовувати `document.body` замість `document.documentElement`.
6666
67-
Luckily, we don't have to remember these peculiarities at all, because the scroll is available in the special properties, `window.pageXOffset/pageYOffset`:
67+
На щастя, нам не потрібно пам’ятати про ці особливості, оскільки прокрутка доступна у спеціальних властивостях `window.pageXOffset/pageYOffset`:
6868
6969
```js run
70-
alert('Current scroll from the top: ' + window.pageYOffset);
71-
alert('Current scroll from the left: ' + window.pageXOffset);
70+
alert('Поточна прокрутка зверху: ' + window.pageYOffset);
71+
alert('Поточна прокрутка зліва: ' + window.pageXOffset);
7272
```
7373
74-
These properties are read-only.
74+
Ці властивості доступні лише для читання.
7575
76-
```smart header="Also available as `window` properties `scrollX` and `scrollY`"
77-
For historical reasons, both properties exist, but they are the same:
78-
- `window.pageXOffset` is an alias of `window.scrollX`.
79-
- `window.pageYOffset` is an alias of `window.scrollY`.
76+
```smart header="Також доступні як властивості `window` `scrollX` та `scrollY`"
77+
З історичних причин обидві властивості існують, але вони однакові:
78+
- `window.pageXOffset` є псевдонімом `window.scrollX`.
79+
- `window.pageYOffset` є псевдонімом `window.scrollY`.
8080
```
8181
82-
## Scrolling: scrollTo, scrollBy, scrollIntoView [#window-scroll]
82+
## Прокрутка: scrollTo, scrollBy, scrollIntoView [#window-scroll]
8383
8484
```warn
85-
To scroll the page with JavaScript, its DOM must be fully built.
85+
Щоб прокручувати сторінку за допомогою JavaScript, її DOM має бути повністю створено.
8686
87-
For instance, if we try to scroll the page with a script in `<head>`, it won't work.
87+
Наприклад, якщо ми спробуємо прокрутити сторінку за допомогою сценарію в `<head>`, це не спрацює.
8888
```
8989
90-
Regular elements can be scrolled by changing `scrollTop/scrollLeft`.
90+
Звичайні елементи можна прокручувати, змінюючи `scrollTop/scrollLeft`.
9191
92-
We can do the same for the page using `document.documentElement.scrollTop/scrollLeft` (except Safari, where `document.body.scrollTop/Left` should be used instead).
92+
Ми можемо зробити те ж саме для сторінки, використовуючи `document.documentElement.scrollTop/scrollLeft` (крім Safari, де замість цього слід використовувати `document.body.scrollTop/Left`).
9393
94-
Alternatively, there's a simpler, universal solution: special methods [window.scrollBy(x,y)](mdn:api/Window/scrollBy) and [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo).
94+
Крім того, є більш просте та універсальне рішення: спеціальні методи [window.scrollBy(x,y)](mdn:api/Window/scrollBy) і [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo) .
9595
96-
- The method `scrollBy(x,y)` scrolls the page *relative to its current position*. For instance, `scrollBy(0,10)` scrolls the page `10px` down.
96+
- Метод `scrollBy(x,y)` прокручує сторінку *відносно її поточної позиції*. Наприклад, `scrollBy(0,10)` прокручує сторінку на `10px` вниз.
9797
9898
```online
99-
The button below demonstrates this:
99+
Кнопка нижче це демонструє:
100100
101101
<button onclick="window.scrollBy(0,10)">window.scrollBy(0,10)</button>
102102
```
103-
- The method `scrollTo(pageX,pageY)` scrolls the page *to absolute coordinates*, so that the top-left corner of the visible part has coordinates `(pageX, pageY)` relative to the document's top-left corner. It's like setting `scrollLeft/scrollTop`.
103+
- Метод `scrollTo(pageX,pageY)` прокручує сторінку *до абсолютних координат*, так що верхній лівий кут видимої частини має координати `(pageX, pageY)` відносно верхнього лівого кута документа. Це те ж саме, що призначити `scrollLeft/scrollTop`.
104104
105-
To scroll to the very beginning, we can use `scrollTo(0,0)`.
105+
Щоб прокрутити до самого початку, ми можемо використовувати `scrollTo(0,0)`.
106106
107107
```online
108108
<button onclick="window.scrollTo(0,0)">window.scrollTo(0,0)</button>
109109
```
110110
111-
These methods work for all browsers the same way.
111+
Ці методи працюють для всіх браузерів однаково.
112112
113113
## scrollIntoView
114114
115-
For completeness, let's cover one more method: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
115+
Для повноти розглянемо ще один метод: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
116116
117-
The call to `elem.scrollIntoView(top)` scrolls the page to make `elem` visible. It has one argument:
117+
Виклик `elem.scrollIntoView(top)` прокручує сторінку таким чином, щоб зробити `elem` видимим. Він має один аргумент:
118118
119-
- If `top=true` (that's the default), then the page will be scrolled to make `elem` appear on the top of the window. The upper edge of the element will be aligned with the window top.
120-
- If `top=false`, then the page scrolls to make `elem` appear at the bottom. The bottom edge of the element will be aligned with the window bottom.
119+
- Якщо `top=true` (це значення за замовчуванням), то сторінка буде прокручена, щоб `elem` з'явився у верхній частині вікна. Верхній край елемента буде вирівняний з верхньою частиною вікна.
120+
- Якщо `top=false`, то сторінка прокручується, щоб `elem` з'явився внизу. Нижній край елемента буде вирівняний з нижньою частиною вікна.
121121
122122
```online
123-
The button below scrolls the page to position itself at the window top:
123+
Кнопка нижче прокручує сторінку, щоб розмістити себе у верхній частині вікна:
124124
125125
<button onclick="this.scrollIntoView()">this.scrollIntoView()</button>
126126
127-
And this button scrolls the page to position itself at the bottom:
127+
А ця кнопка прокручує сторінку, щоб розмістити себе у нижній частині вікна:
128128
129129
<button onclick="this.scrollIntoView(false)">this.scrollIntoView(false)</button>
130130
```
131131
132-
## Forbid the scrolling
132+
## Заборона прокручування
133133
134-
Sometimes we need to make the document "unscrollable". For instance, when we need to cover the page with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document.
134+
Іноді нам потрібно зробити документ «непрокручуваним». Наприклад, коли нам потрібно закрити сторінку великим повідомленням, яке вимагає негайної уваги, і ми хочемо, щоб відвідувач взаємодіяв з цим повідомленням, а не з документом.
135135
136-
To make the document unscrollable, it's enough to set `document.body.style.overflow = "hidden"`. The page will "freeze" at its current scroll position.
136+
Щоб зробити документ недоступним для прокручування, достатньо встановити `document.body.style.overflow = "hidden"`. Сторінка «завмере» у поточній позиції прокручування.
137137
138138
```online
139-
Try it:
139+
Спробуй:
140140
141141
<button onclick="document.body.style.overflow = 'hidden'">document.body.style.overflow = 'hidden'</button>
142142
143143
<button onclick="document.body.style.overflow = ''">document.body.style.overflow = ''</button>
144144
145-
The first button freezes the scroll, while the second one releases it.
145+
Перша кнопка зупиняє прокрутку, а друга відновлює.
146146
```
147147
148-
We can use the same technique to freeze the scroll for other elements, not just for `document.body`.
148+
Ми можемо використовувати ту саму техніку, щоб заморозити прокрутку для інших елементів, а не лише для `document.body`.
149149
150-
The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free and the content "jumps" to fill it.
150+
Недоліком цього методу є те, що смуга прокрутки зникає. Якщо вона займала деякий простір, то це місце звільняється, і вміст «стрибає», щоб заповнити його.
151151
152-
That looks a bit odd, but can be worked around if we compare `clientWidth` before and after the freeze. If it increased (the scrollbar disappeared), then add `padding` to `document.body` in place of the scrollbar to keep the content width the same.
152+
Це виглядає трохи дивно, але це можна обійти, якщо порівняти `clientWidth` до і після заборони прокручування. Якщо ширина збільшилась (смуга прокрутки зникла), додайте `padding` до `document.body` замість смуги прокрутки, щоб зберегти ширину вмісту такою ж.
153153
154-
## Summary
154+
## Підсумки
155155
156-
Geometry:
156+
Геометрія:
157157
158-
- Width/height of the visible part of the document (content area width/height): `document.documentElement.clientWidth/clientHeight`
159-
- Width/height of the whole document, with the scrolled out part:
158+
- Ширина/висота видимої частини документа (ширина/висота області вмісту): `document.documentElement.clientWidth/clientHeight`
159+
- Ширина/висота всього документа з прокрученою частиною:
160160
161161
```js
162162
let scrollHeight = Math.max(
@@ -166,11 +166,11 @@ Geometry:
166166
);
167167
```
168168
169-
Scrolling:
169+
Прокрутка:
170170
171-
- Read the current scroll: `window.pageYOffset/pageXOffset`.
172-
- Change the current scroll:
171+
- Прочитати поточну прокрутку: `window.pageYOffset/pageXOffset`.
172+
- Змінити поточну прокрутку:
173173
174-
- `window.scrollTo(pageX,pageY)` -- absolute coordinates,
175-
- `window.scrollBy(x,y)` -- scroll relative the current place,
176-
- `elem.scrollIntoView(top)` -- scroll to make `elem` visible (align with the top/bottom of the window).
174+
- `window.scrollTo(pageX,pageY)` -- абсолютні координати,
175+
- `window.scrollBy(x,y)` -- прокрутити відносно поточного місця,
176+
- `elem.scrollIntoView(top)` -- прокрутити, щоб зробити `elem` видимим (вирівняти з верхньою/нижньою частиною вікна).

0 commit comments

Comments
 (0)