Skip to content

Commit caede8f

Browse files
committed
up
1 parent 3e33cd6 commit caede8f

File tree

12 files changed

+70
-244
lines changed

12 files changed

+70
-244
lines changed
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
Решение: `elem.scrollHeight - elem.scrollTop - elem.clientHeight`.
1+
The solution is:
2+
3+
```js
4+
let scrollBottom = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
5+
```

2-ui/1-document/15-size-and-scroll/1-get-scroll-height-bottom/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ importance: 5
22

33
---
44

5-
# Найти размер прокрутки снизу
5+
# What's the scroll from the bottom?
66

7-
Свойство `elem.scrollTop` содержит размер прокрученной области при отсчете сверху. А как подсчитать размер прокрутки снизу?
7+
The `elem.scrollTop` property is the size of the scrolled out part from the top. How to get "`scrollBottom`" -- the size from the bottom?
88

9-
Напишите соответствующее выражение для произвольного элемента `elem`.
9+
Write the code that works for an arbitrary `elem`.
1010

11-
Проверьте: если прокрутки нет вообще или элемент полностью прокручен -- оно должно давать ноль.
11+
P.S. Please check your code: if there's no scroll or the element is fully scrolled down, then it should return `0`.
Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1-
Создадим элемент с прокруткой, но без `border` и `padding`. Тогда разница между его полной шириной `offsetWidth` и внутренней `clientWidth` будет равна как раз прокрутке:
1+
To get the scrollbar width, we can create an element with the scroll, but without borders and paddings.
2+
3+
Then the difference between its full width `offsetWidth` and the inner content area width `clientWidth` will be exactly the scrollbar:
24

35
```js run
4-
// создадим элемент с прокруткой
5-
var div = document.createElement('div');
6+
// create a div with the scroll
7+
let div = document.createElement('div');
68

79
div.style.overflowY = 'scroll';
810
div.style.width = '50px';
911
div.style.height = '50px';
1012

11-
// при display:none размеры нельзя узнать
12-
// нужно, чтобы элемент был видим,
13-
// visibility:hidden - можно, т.к. сохраняет геометрию
14-
div.style.visibility = 'hidden';
13+
// must put it in the document, otherwise sizes will be 0
14+
document.body.append(div);
15+
let scrollWidth = div.offsetWidth - div.clientWidth;
1516

16-
document.body.appendChild(div);
17-
var scrollWidth = div.offsetWidth - div.clientWidth;
18-
document.body.removeChild(div);
17+
div.remove();
1918

20-
alert( scrollWidth );
19+
alert(scrollWidth);
2120
```
22-

2-ui/1-document/15-size-and-scroll/2-scrollbar-width/task.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ importance: 3
22

33
---
44

5-
# Узнать ширину полосы прокрутки
5+
# What is the scrollbar width?
66

7-
Напишите код, который возвращает ширину стандартной полосы прокрутки. Именно самой полосы, где ползунок. Обычно она равна `16px`, в редких и мобильных браузерах может колебаться от `14px` до `18px`, а кое-где даже равна `0px`.
7+
Write the code that returns the width of a standard scrollbar.
88

9-
P.S. Ваш код должен работать на любом HTML-документе, независимо от его содержимого.
9+
For Windows it usually varies between `12px` and `20px`, but if the browser reserves no space for it, then it may be `0px`.
10+
11+
P.S. The code should work in any HTML document, do not depend on its content.

2-ui/1-document/15-size-and-scroll/3-div-placeholder/solution.md

Lines changed: 0 additions & 29 deletions
This file was deleted.

2-ui/1-document/15-size-and-scroll/3-div-placeholder/solution.view/index.html

Lines changed: 0 additions & 50 deletions
This file was deleted.

2-ui/1-document/15-size-and-scroll/3-div-placeholder/source.view/index.html

Lines changed: 0 additions & 37 deletions
This file was deleted.

2-ui/1-document/15-size-and-scroll/3-div-placeholder/task.md

Lines changed: 0 additions & 50 deletions
This file was deleted.
Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,42 @@
1-
При абсолютном позиционировании мяча внутри поля его координаты `left/top` отсчитываются от **внутреннего** угла поля, например верхнего-левого:
1+
The ball has `position:absolute`. It means that its `left/top` coordinates are measured from the nearest positioned element, that is `#field` (because it has `position:relative`).
22

3-
![](field.png)
3+
The coordinates start from the inner left-upper corner of the field:
44

5-
Метрики для внутренней зоны поля -- это `clientWidth/Height`.
5+
![](field.png)
66

7-
Центр - это `(clientWidth/2, clientHeight/2)`.
7+
The inner field width/height is `clientWidth/clientHeight`. So the field center has coordinates `(clientWidth/2, clientHeight/2)`.
88

9-
Но если мы установим мячу такие значения `ball.style.left/top`, то в центре будет не сам мяч, а его левый верхний угол:
9+
...But if we set such values to `ball.style.left/top`, then not the ball as a whole, but the left-upper edge of the ball is in the center:
1010

1111
```js
12-
var ball = document.getElementById('ball');
13-
var field = document.getElementById('field');
14-
1512
ball.style.left = Math.round(field.clientWidth / 2) + 'px';
1613
ball.style.top = Math.round(field.clientHeight / 2) + 'px';
1714
```
1815

19-
[iframe hide="Нажмите, чтобы посмотреть текущий результат" height=180 src="ball-half"]
16+
Here's how it looks:
2017

21-
Для того, чтобы центр мяча находился в центре поля, нам нужно сместить мяч на половину его ширины влево и на половину его высоты вверх.
18+
[iframe height=180 src="ball-half"]
2219

23-
```js
24-
var ball = document.getElementById('ball');
25-
var field = document.getElementById('field');
20+
To align the ball center with the center of the field, we should move the ball to the half of its width to the left and to the half of its height to the top:
2621

22+
```js
2723
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px';
2824
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px';
2925
```
3026

31-
**Внимание, подводный камень!**
27+
**Attention: the pitfall!**
3228

33-
Код выше стабильно работать не будет, потому что `IMG` идет без ширины/высоты:
29+
The code won't work reliably while `<img>` width/height is not given to the browser:
3430

3531
```html
3632
<img src="ball.png" id="ball">
3733
```
3834

39-
**Высота и ширина изображения неизвестны браузеру до тех пор, пока оно не загрузится, если размер не указан явно.**
35+
When the browser meets such a tag, it tries to figure out its width/height. Either from the `<img width=... height=...>` attributes or (if not given) from CSS.
36+
37+
If none is given, then the sizes are assumed to be `0` until the image loads.
38+
39+
TODO
4040

4141
После первой загрузки изображение уже будет в кеше браузера, и его размеры будут известны. Но когда браузер впервые видит документ -- он ничего не знает о картинке, поэтому значение `ball.offsetWidth` равно `0`. Вычислить координаты невозможно.
4242

@@ -47,4 +47,3 @@ ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'p
4747
```
4848

4949
Теперь браузер всегда знает ширину и высоту, так что все работает. Тот же эффект дало бы указание размеров в CSS.
50-

2-ui/1-document/15-size-and-scroll/4-put-ball-in-center/task.md

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,19 @@ importance: 5
22

33
---
44

5-
# Поместите мяч в центр поля
5+
# Place the ball in the field center
66

7-
Поместите мяч в центр поля.
8-
9-
Исходный документ выглядит так:
7+
Here's how the source document looks:
108

119
[iframe src="source" edit link height=180]
1210

13-
**Используйте JavaScript, чтобы поместить мяч в центр:**
11+
What are coordinates of the field center?
12+
13+
Calculate them and use to place the ball into the center of the field:
1414

1515
[iframe src="solution" height=180]
1616

17-
- Менять CSS нельзя, мяч должен переносить в центр ваш скрипт, через установку нужных стилей элемента.
18-
- JavaScript-код должен работать при разных размерах мяча (`10`, `20`, `30` пикселей) без изменений.
19-
- JavaScript-код должен работать при различных размерах и местоположениях поля на странице без изменений. Также он не должен зависеть от ширины рамки поля `border`.
17+
- The element should be moved by JavaScript, not CSS.
18+
- The code should work with any ball size (`10`, `20`, `30` pixels) and any field size, not be bound to the given values.
2019

21-
P.S. Да, центрирование можно сделать при помощи чистого CSS, но задача именно на JavaScript. Далее будут другие темы и более сложные ситуации, когда JavaScript будет уже точно необходим, это -- своего рода "разминка".
20+
P.S. Sure, centering could be done with CSS, but here we want exactly JavaScript. Further we'll meet other topics and more complex situations when JavaScript must be used. Here we do a "warm-up".

0 commit comments

Comments
 (0)