diff --git a/1-js/1-getting-started/1-intro/limitations.svg b/1-js/1-getting-started/1-intro/limitations.svg index 08c7a56c..f797f757 100644 --- a/1-js/1-getting-started/1-intro/limitations.svg +++ b/1-js/1-getting-started/1-intro/limitations.svg @@ -1 +1,93 @@ -Slice 1Created with Sketch.http://javascript.info&lt;script&gt;...&lt;/script&gt;http://gmail.comhttp://javascript.info \ No newline at end of file + + + + limitations.svg + Created with bin/sketchtool. + + + + + + + + http://javascript.info + + + <script> + ... + </script> + + + + + + + + http://gmail.com + + + + + + + + + + + + + + + + + + + + + + + + http://javascript.info + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/1-js/2-first-steps/5-variables/variable-change.svg b/1-js/2-first-steps/5-variables/variable-change.svg index a2ef0b76..c19d0827 100644 --- a/1-js/2-first-steps/5-variables/variable-change.svg +++ b/1-js/2-first-steps/5-variables/variable-change.svg @@ -1,34 +1,37 @@ - + + + variable-change.svg + Created with bin/sketchtool. - - - - - + + + + + - - + + "World!" - - + + "Hello!" - + - + Message - - - - - - + + + + + + diff --git a/1-js/2-first-steps/5-variables/variable.svg b/1-js/2-first-steps/5-variables/variable.svg index 761e7951..27528808 100644 --- a/1-js/2-first-steps/5-variables/variable.svg +++ b/1-js/2-first-steps/5-variables/variable.svg @@ -1,21 +1,24 @@ - + + + variable.svg + Created with bin/sketchtool. - - - + + + - - + + - - + + "Hello!" - + - + Message diff --git a/1-js/3-writing-js/2-coding-style/code-style.svg b/1-js/3-writing-js/2-coding-style/code-style.svg index d2b65d84..64fa7c07 100644 --- a/1-js/3-writing-js/2-coding-style/code-style.svg +++ b/1-js/3-writing-js/2-coding-style/code-style.svg @@ -1,85 +1,88 @@ - + + + code-style.svg + Created with bin/sketchtool. - - - - - - - - - - + + + + + + + + + + 2 - - - - + + + + Между именем функции и скобкой ( нет пробела - + - + Отступ 2 пробела - + - + Пробел после for - + - + } else { без перевода строки - + - + Пробелы вокруг вложенного вызова - + - + - + пустая строка между логическими блоками - + - + длина строки не более 80 символов - + - + точка с запятой ; обязательна - + - + Фигурная скобка { на той же строке, через пробел - + - + - + Пробел между параметрами - + - + Пробел между параметрами diff --git a/1-js/3-writing-js/2-coding-style/figure-bracket-style.svg b/1-js/3-writing-js/2-coding-style/figure-bracket-style.svg index bf3382a5..8dc4e240 100644 --- a/1-js/3-writing-js/2-coding-style/figure-bracket-style.svg +++ b/1-js/3-writing-js/2-coding-style/figure-bracket-style.svg @@ -1 +1,32 @@ -Slice 1Created with Sketch.Плохо!Фигурные скобки не имеют смыслаВ одну строку без скобок - приемлемо,если эта строка короткаяСамый лучший вариант \ No newline at end of file + + + + figure-bracket-style.svg + Created with bin/sketchtool. + + + + + + + Плохо! + Фигурные скобки не имеют смысла + + + + + + + + В одну строку без скобок - приемлемо, + если эта строка короткая + + + Самый лучший вариант + + + + + + + \ No newline at end of file diff --git a/1-js/4-data-structures/4-object/object-person-1.svg b/1-js/4-data-structures/4-object/object-person-1.svg index 8595ec01..9a407ba2 100644 --- a/1-js/4-data-structures/4-object/object-person-1.svg +++ b/1-js/4-data-structures/4-object/object-person-1.svg @@ -1,15 +1,18 @@ - + + + object-person-1.svg + Created with bin/sketchtool. - - - - - - + + + + + + name - + age diff --git a/1-js/4-data-structures/4-object/object-person-2.svg b/1-js/4-data-structures/4-object/object-person-2.svg index 42925ca6..0fca6a0d 100644 --- a/1-js/4-data-structures/4-object/object-person-2.svg +++ b/1-js/4-data-structures/4-object/object-person-2.svg @@ -1,11 +1,14 @@ - + + + object-person-2.svg + Created with bin/sketchtool. - - - - - + + + + + name diff --git a/1-js/4-data-structures/4-object/object-person-empty.svg b/1-js/4-data-structures/4-object/object-person-empty.svg index 9240ecd4..20b239c9 100644 --- a/1-js/4-data-structures/4-object/object-person-empty.svg +++ b/1-js/4-data-structures/4-object/object-person-empty.svg @@ -1,16 +1,19 @@ - + + + object-person-empty.svg + Created with bin/sketchtool. - - - - + + + + пусто - + person - + diff --git a/1-js/4-data-structures/4-object/object.svg b/1-js/4-data-structures/4-object/object.svg index 82f41f43..6d671c19 100644 --- a/1-js/4-data-structures/4-object/object.svg +++ b/1-js/4-data-structures/4-object/object.svg @@ -1,19 +1,22 @@ - + + + object.svg + Created with bin/sketchtool. - - - - - - - + + + + + + + ключ1 - + ключ2 - + ключ3 diff --git a/1-js/4-data-structures/6-object-reference/variable-contains-reference.svg b/1-js/4-data-structures/6-object-reference/variable-contains-reference.svg index 3f67cd35..73434aa6 100644 --- a/1-js/4-data-structures/6-object-reference/variable-contains-reference.svg +++ b/1-js/4-data-structures/6-object-reference/variable-contains-reference.svg @@ -1,26 +1,29 @@ - + + + variable-contains-reference.svg + Created with bin/sketchtool. - - - - - - + + + + + + - + User - - - - - + + + + + name - - - + + + diff --git a/1-js/4-data-structures/6-object-reference/variable-copy-reference.svg b/1-js/4-data-structures/6-object-reference/variable-copy-reference.svg index 80ce9d79..f79f03bc 100644 --- a/1-js/4-data-structures/6-object-reference/variable-copy-reference.svg +++ b/1-js/4-data-structures/6-object-reference/variable-copy-reference.svg @@ -1,46 +1,49 @@ - + + + variable-copy-reference.svg + Created with bin/sketchtool. - - - - - + + + + + name - - + + - + User - + - + - - - - + + + + - + Admin - - - + + + - - - + + + diff --git a/1-js/4-data-structures/6-object-reference/variable-copy-value.svg b/1-js/4-data-structures/6-object-reference/variable-copy-value.svg index 4fdbaaa0..83b9e7d1 100644 --- a/1-js/4-data-structures/6-object-reference/variable-copy-value.svg +++ b/1-js/4-data-structures/6-object-reference/variable-copy-value.svg @@ -1,35 +1,38 @@ - + + + variable-copy-value.svg + Created with bin/sketchtool. - - - + + + - - + + - - + + "Привет!" - + - + Message - - - + + + - - + + "Привет!" - - + + Phrase diff --git a/1-js/4-data-structures/7-array/array-pop.svg b/1-js/4-data-structures/7-array/array-pop.svg index 57d640e1..d8c3ddc0 100644 --- a/1-js/4-data-structures/7-array/array-pop.svg +++ b/1-js/4-data-structures/7-array/array-pop.svg @@ -1,65 +1,68 @@ - + + + array-pop.svg + Created with bin/sketchtool. - - - - - + + + + + 0 - + 1 - - + + 2 - - + + 3 - + "Яблоко" - + "Апельсин" - + "Груша" - + "Лимон" - + length = 4 - - + + очистить - - - + + + 0 - + 1 - - + + 2 - + "Яблоко" - + "Апельсин" - + "Груша" - + length = 3 diff --git a/1-js/4-data-structures/7-array/array-shift.svg b/1-js/4-data-structures/7-array/array-shift.svg index 0d65ce64..b29495d9 100644 --- a/1-js/4-data-structures/7-array/array-shift.svg +++ b/1-js/4-data-structures/7-array/array-shift.svg @@ -1,100 +1,103 @@ - + + + array-shift.svg + Created with bin/sketchtool. - - - + + + 1 - - + + 2 - - + + 3 - + "Апельсин" - + "Груша" - + "Лимон" - + length = 4 - - - + + + 0 - + 1 - - + + 2 - - + + 3 - + "Апельсин" - + "Груша" - + "Лимон" - + length = 4 - - + + очистить - + переместить элементы влево - - - + + + 0 - + "Яблоко" - - - - + + + + 0 - + 1 - - + + 2 - + "Апельсин" - + "Груша" - + "Лимон" - + length = 3 diff --git a/1-js/4-data-structures/7-array/array-speed.svg b/1-js/4-data-structures/7-array/array-speed.svg index 8847322c..cbaa8815 100644 --- a/1-js/4-data-structures/7-array/array-speed.svg +++ b/1-js/4-data-structures/7-array/array-speed.svg @@ -1,46 +1,49 @@ - + + + array-speed.svg + Created with bin/sketchtool. - - - - - + + + + + 0 - + 1 - - + + 2 - - + + 3 - - - + + + pop - - - + + + unshift - - - + + + push - - - + + + shift - - + + \ No newline at end of file diff --git a/1-js/4-data-structures/7-array/queue.svg b/1-js/4-data-structures/7-array/queue.svg index e9cca8db..c3c4399b 100644 --- a/1-js/4-data-structures/7-array/queue.svg +++ b/1-js/4-data-structures/7-array/queue.svg @@ -1,14 +1,17 @@ - + + + queue.svg + Created with bin/sketchtool. - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/1-js/4-data-structures/7-array/stack.svg b/1-js/4-data-structures/7-array/stack.svg index beb45167..f2aa07a8 100644 --- a/1-js/4-data-structures/7-array/stack.svg +++ b/1-js/4-data-structures/7-array/stack.svg @@ -1,14 +1,17 @@ - + + + stack.svg + Created with bin/sketchtool. - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/1-js/4-data-structures/8-array-methods/9-output-single-linked-list/linked-list.svg b/1-js/4-data-structures/8-array-methods/9-output-single-linked-list/linked-list.svg index 609eedcd..af4b480c 100644 --- a/1-js/4-data-structures/8-array-methods/9-output-single-linked-list/linked-list.svg +++ b/1-js/4-data-structures/8-array-methods/9-output-single-linked-list/linked-list.svg @@ -1,57 +1,60 @@ - + + + linked-list.svg + Created with bin/sketchtool. - - - - + + + + value - + 1 - + - + next - - + + value - + 2 - + - + next - - + + value - + 3 - + - + next - - + + value - + 4 - + - + next - + null diff --git a/1-js/4-data-structures/9-array-iteration/reduce.svg b/1-js/4-data-structures/9-array-iteration/reduce.svg index d0e20e10..b50624d9 100644 --- a/1-js/4-data-structures/9-array-iteration/reduce.svg +++ b/1-js/4-data-structures/9-array-iteration/reduce.svg @@ -1,61 +1,64 @@ - + + + reduce.svg + Created with bin/sketchtool. - - - - + + + + 1 - + sum 0 current 1 - - + + 2 - + sum 0+1 current 2 - - + + 3 - + sum 0+1+2 current 3 - - + + 4 - + sum 0+1+2+3 current 4 - - + + 5 - + sum 0+1+2+3+4 current 5 - + - + 0+1+2+3+4+5 = 15 diff --git a/1-js/5-functions-closures/6-memory-management/family-no-family.svg b/1-js/5-functions-closures/6-memory-management/family-no-family.svg index 1011677b..bb11547c 100644 --- a/1-js/5-functions-closures/6-memory-management/family-no-family.svg +++ b/1-js/5-functions-closures/6-memory-management/family-no-family.svg @@ -1,61 +1,64 @@ - + + + family-no-family.svg + Created with bin/sketchtool. - - - + + + - - + + window - + Корень - - + + Object - - + + Object - + father - + wife - + name: "Василий" - - + + name: "Мария" - + mother - + Object - + - + - + husband - + - - + + family: null - - - - + + + + diff --git a/1-js/5-functions-closures/6-memory-management/family-no-father-2.svg b/1-js/5-functions-closures/6-memory-management/family-no-father-2.svg index 0b72eb65..e1dc984e 100644 --- a/1-js/5-functions-closures/6-memory-management/family-no-father-2.svg +++ b/1-js/5-functions-closures/6-memory-management/family-no-father-2.svg @@ -1,35 +1,38 @@ - + + + family-no-father-2.svg + Created with bin/sketchtool. - - - - + + + + window - + Корень - - + + Object - + family - - + + name: "Мария" - + mother - + Object - + - + diff --git a/1-js/5-functions-closures/6-memory-management/family-no-father.svg b/1-js/5-functions-closures/6-memory-management/family-no-father.svg index ccb96efd..c461cfaa 100644 --- a/1-js/5-functions-closures/6-memory-management/family-no-father.svg +++ b/1-js/5-functions-closures/6-memory-management/family-no-father.svg @@ -1,53 +1,56 @@ - + + + family-no-father.svg + Created with bin/sketchtool. - - - - + + + + window - + Корень - - + + Object - - + + Object - + wife - + family - + name: "Василий" - - + + name: "Мария" - + mother - + Object - + - + - + - - - - - + + + + + diff --git a/1-js/5-functions-closures/6-memory-management/family.svg b/1-js/5-functions-closures/6-memory-management/family.svg index 82132d76..43cc08f3 100644 --- a/1-js/5-functions-closures/6-memory-management/family.svg +++ b/1-js/5-functions-closures/6-memory-management/family.svg @@ -1,57 +1,60 @@ - + + + family.svg + Created with bin/sketchtool. - - - + + + - - + + window - + Корень - - + + Object - - + + Object - + father - + wife - + family - + name: "Василий" - - + + name: "Мария" - + mother - + Object - + - + - + - + husband - + diff --git a/1-js/7-js-misc/3-setTimeout-setInterval/setinterval-interval.svg b/1-js/7-js-misc/3-setTimeout-setInterval/setinterval-interval.svg index 6340f1c2..820dc80e 100644 --- a/1-js/7-js-misc/3-setTimeout-setInterval/setinterval-interval.svg +++ b/1-js/7-js-misc/3-setTimeout-setInterval/setinterval-interval.svg @@ -1,38 +1,41 @@ - + + + setinterval-interval.svg + Created with bin/sketchtool. - - - - - + + + + + func(1) - - - - + + + + func(2) - - - - + + + + func(3) - - - + + + 100 - + 200 - + 300 - - + + \ No newline at end of file diff --git a/1-js/7-js-misc/3-setTimeout-setInterval/settimeout-interval.svg b/1-js/7-js-misc/3-setTimeout-setInterval/settimeout-interval.svg index c57231a5..512dbf7e 100644 --- a/1-js/7-js-misc/3-setTimeout-setInterval/settimeout-interval.svg +++ b/1-js/7-js-misc/3-setTimeout-setInterval/settimeout-interval.svg @@ -1,45 +1,48 @@ - + + + settimeout-interval.svg + Created with bin/sketchtool. - - - - - + + + + + func(1) - - - - + + + + func(2) - - - - + + + + func(3) - - - - - + + + + + 100 - + 100 - - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/1-js/9-prototypes/1-prototype/proto-animal-rabbit.svg b/1-js/9-prototypes/1-prototype/proto-animal-rabbit.svg index c33f2e4e..b50edd98 100644 --- a/1-js/9-prototypes/1-prototype/proto-animal-rabbit.svg +++ b/1-js/9-prototypes/1-prototype/proto-animal-rabbit.svg @@ -1,25 +1,28 @@ - + + + proto-animal-rabbit.svg + Created with bin/sketchtool. - - - - + + + + eats: true - + animal - - + + jumps: true - + rabbit - + - + __proto__ diff --git a/1-js/9-prototypes/3-native-prototypes/native-prototypes-array-tostring.svg b/1-js/9-prototypes/3-native-prototypes/native-prototypes-array-tostring.svg index 1876d4c5..19195783 100644 --- a/1-js/9-prototypes/3-native-prototypes/native-prototypes-array-tostring.svg +++ b/1-js/9-prototypes/3-native-prototypes/native-prototypes-array-tostring.svg @@ -1,37 +1,40 @@ - + + + native-prototypes-array-tostring.svg + Created with bin/sketchtool. - - - - + + + + toString: function ... - + Array.prototype - - + + toString: function ... - + Object.prototype - - + + - + __proto__ - + - + __proto__ - - + + [1, 2, 3] diff --git a/1-js/9-prototypes/3-native-prototypes/native-prototypes-classes.svg b/1-js/9-prototypes/3-native-prototypes/native-prototypes-classes.svg index 2dc19808..7bd483bb 100644 --- a/1-js/9-prototypes/3-native-prototypes/native-prototypes-classes.svg +++ b/1-js/9-prototypes/3-native-prototypes/native-prototypes-classes.svg @@ -1,90 +1,93 @@ - + + + native-prototypes-classes.svg + Created with bin/sketchtool. - - - - + + + + toString: function другие методы объектов - + Object.prototype - + - + __proto__ - + - + null - - + + slice: function другие методы массивов - + __proto__ - + Array.prototype - - + + __proto__ - + apply: function другие методы функций - + Function.prototype - - + + toFixed: function другие методы чисел - + Number.prototype - + __proto__ - + - + - - + + [1, 2, 3] - - + + function f(args) { ... } - - + + 5 - + - + __proto__ - + - + __proto__ - + - + __proto__ diff --git a/1-js/9-prototypes/3-native-prototypes/native-prototypes-object.svg b/1-js/9-prototypes/3-native-prototypes/native-prototypes-object.svg index edd249c7..071eecf5 100644 --- a/1-js/9-prototypes/3-native-prototypes/native-prototypes-object.svg +++ b/1-js/9-prototypes/3-native-prototypes/native-prototypes-object.svg @@ -1,31 +1,34 @@ - + + + native-prototypes-object.svg + Created with bin/sketchtool. - - - - + + + + toString: function другие методы объектов - + Object.prototype - - + + obj - + - + __proto__ - + - + __proto__ - + null diff --git a/1-js/9-prototypes/5-class-inheritance/class-inheritance-array-object.svg b/1-js/9-prototypes/5-class-inheritance/class-inheritance-array-object.svg index ddc051ba..2580fa85 100644 --- a/1-js/9-prototypes/5-class-inheritance/class-inheritance-array-object.svg +++ b/1-js/9-prototypes/5-class-inheritance/class-inheritance-array-object.svg @@ -1,39 +1,42 @@ - + + + class-inheritance-array-object.svg + Created with bin/sketchtool. - - - - + + + + slice: function ... - + Array.prototype - + arr - - + + hasOwnProperty: function ... - + Object.prototype - - + + - + __proto__ - + - + __proto__ - + [1, 2, 3] diff --git a/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-animal.svg b/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-animal.svg index 25025019..ab9c4ead 100644 --- a/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-animal.svg +++ b/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-animal.svg @@ -1,38 +1,41 @@ - + + + class-inheritance-rabbit-animal.svg + Created with bin/sketchtool. - - - - + + + + jump: function - + Rabbit.prototype - + rabbit - - + + run: function stop: function - + Animal.prototype - - + + - + __proto__ - + - + __proto__ - + name: "Кроль" speed: 0 diff --git a/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-run-animal.svg b/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-run-animal.svg index 8ed1d23b..d5476cd2 100644 --- a/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-run-animal.svg +++ b/1-js/9-prototypes/5-class-inheritance/class-inheritance-rabbit-run-animal.svg @@ -1,40 +1,43 @@ - + + + class-inheritance-rabbit-run-animal.svg + Created with bin/sketchtool. - - - - + + + + jump: function run: function - + Rabbit.prototype - + rabbit - - + + run: function stop: function - + Animal.prototype - - + + - + __proto__ - + - + __proto__ - + name: "Кроль" speed: 0 diff --git a/2-ui/1-document/15-metrics/article.md b/2-ui/1-document/15-metrics/article.md index 9a598825..e6592e5c 100644 --- a/2-ui/1-document/15-metrics/article.md +++ b/2-ui/1-document/15-metrics/article.md @@ -6,9 +6,9 @@ [cut] -## Метрики: образец документа +## Образец документа -Мы будем использовать для примера вот такой элемент, у которого есть рамка (border), поля (padding), отступы (margin) и прокрутка: +Мы будем использовать для примера вот такой элемент, у которого есть рамка (border), поля (padding), и прокрутка: ```html
@@ -17,23 +17,45 @@ ``` +У него нет отступов `margin`, в этой главе они не важны, так как метрики касаются именно размеров самого элемента, отступы в них не учитываются. + Результат выглядит так: - + -Вы можете открыть этот документ [edit src="metric"]в песочнице[/edit]. +Вы можете открыть [edit src="metric"]этот документ в песочнице[/edit]. + +[smart header="Внимание, полоса прокрутки!"] +В иллюстрации выше намеренно продемонстрирован самый сложный и полный случай, когда у элемента есть ещё и полоса прокрутки. + +В этом случае полоса прокрутки "отодвигает" содержимое вместе с `padding` влево, отбирая у него место. + +Именно поэтому ширина содержимого обозначена как `content width` и равна `284px`, а не `300px`, как в CSS. + +Точное значение получено в предположении, что ширина полосы прокрутки равна `16px`, то есть после её вычитания на содержимое остаётся `300 - 16 = 284px`. Конечно, она сильно зависит от браузера, устройства, ОС. + +Мы должны в точности понимать, что происходит с размерами элемента при наличии полосы прокрутки, поэтому на картинке выше это отражено. +[/smart] + +[smart header="Поле `padding` заполнено текстом"] +Обычно поля `padding` изображают пустыми, но так как текста много, то он заполняет нижнее поле `padding-bottom` в примере выше. + +Во избежание путаницы заметим, что `padding` там, всё же, есть. Поля `padding` по CSS в элементе выше одинаковы со всех сторон. А такое заполнение -- нормальное поведение браузера. +[/smart] + +## Метрики У элементов существует ряд свойств, содержащих их внешние и внутренние размеры. Мы будем называть их "метриками". @@ -41,55 +63,57 @@ Вот общая картина: + На картинке все они с трудом помещаются, но, как мы увидим далее, их значения просты и понятны. Будем исследовать их снаружи элемента и вовнутрь. -## offsetWidth/Height - -Эти свойства дают "внешнюю" ширину/высоту элемента, то есть его полный размер, включая рамки `border`, но исключая внешние отступы `margin`. - -В примере выше: - - - ## offsetParent, offsetLeft/Top -[warn header="Используются редко..."] -Ситуации, когда эти свойства нужны, можно перечислить по пальцам. Они возникают действительно редко. Как правило, эти свойства используют по ошибке, потому что не знают средств правильной работы с координатами, о которых мы поговорим позже. -[/warn] +Ситуации, когда эти свойства нужны, можно перечислить по пальцам. Они возникают действительно редко. Как правило, эти свойства используют, потому что не знают средств правильной работы с координатами, о которых мы поговорим позже. -В `offsetParent` -- ссылка родительский элемент в смысле отображения на странице. +Несмотря на то, что эти свойства нужны реже всего, они -- самые "внешние", поэтому начнём с них. + +**В `offsetParent` находится ссылка родительский элемент в смысле отображения на странице.** Уточним, что имеется в виду. -Когда браузер рисует страницу, то он высчитывает дерево расположения элементов, иначе говоря "дерево геометрии" или "дерево рендеринга". +Когда браузер рисует страницу, то он высчитывает дерево расположения элементов, иначе говоря "дерево геометрии" или "дерево рендеринга", которое содержит всю информацию о размерах. -Обычно элементы вложены друг в друга и структура дерева рендеринга повторяет DOM. +При этом одни элементы естественным образом рисуются внутри других. Но, к примеру, если у элемента стоит `position:absolute`, то его расположение вычисляется уже не относительно непосредственного родителя `parentNode`, а относительно ближайшего позиционированного элемента (т.е. свойство `position` которого не равно `static`), или `BODY`, если такой отсутствует. -Но, к примеру, если у элемента стоит `position: absolute`, то его расположение вычисляется уже не относительно непосредственного родителя `parentNode`, а относительно ближайшего позиционированного элемента (т.е. свойство `position` которого не равно `static`), или `BODY`, если таковой отсутствует. +Получается, что элемент имеет в дополнение к обычному родителю в DOM -- ещё одного "родителя по позиционированию", то есть относительно которого он рисуется. Этот элемент и будет в свойстве `offsetParent`. -Получается, что элемент имеет в дополнение к родителю в DOM -- ещё одного "родителя" в плане позиционирования, то есть относительно которого он рисуется. Этот элемент и будет в свойстве `offsetParent`. +**Свойства `offsetLeft/Top` задают смещение относительно `offsetParent`.** -Свойства `offsetLeft/Top` задают смещение относительно `offsetParent`. - -В примере ниже внешний `
` является родителем внутреннего по позиционированию, и отступ от него будет в `offsetLeft/Top`: +В примере ниже внутренний `
` имеет DOM-родителя `
`, но `offsetParent` у него `
`, и сдвиги относительно его верхнего-левого угла будут в `offsetLeft/Top`: ```html -
+
-
...
+
...
-
+
``` - + + +## offsetWidth/Height + +Теперь переходим к самому элементу. + +Эти два свойства -- самые простые. Они содержат "внешнюю" ширину/высоту элемента, то есть его полный размер, включая рамки `border`. + + + +Для нашего элемента: +
    +
  • `offsetWidth = 390` -- внешняя ширина блока, её можно получить сложением CSS-ширины (`300px`, но её часть на рисунке выше отнимает прокрутка, поэтому `284 + 16`), полей(`2*20px`) и рамок (`2*25px`).
  • +
  • `offsetHeight = 290` -- внешняя высота блока.
  • +
[smart header="Метрики для невидимых элементов равны нулю."] @@ -98,7 +122,7 @@ Для элементов с `display:none` или находящихся вне документа дерево рендеринга не строится. Для них метрики равны нулю. Кстати, и `offsetParent` для таких элементов тоже `null`. -Это дает нам **замечательный способ для проверки, виден ли элемент**: +**Это дает нам замечательный способ для проверки, виден ли элемент**: ```js function isHidden(elem) @@ -116,11 +140,11 @@ function isHidden(elem) -### clientTop/Left +## clientTop/Left -Отступ внутренней части элемента от внешней. +Далее внутри элемента у нас рамки `border`. -Другими словами, это ширина верхней/левой рамки(border) в пикселях. +Для них есть свойства-метрики `clientTop` и `clientLeft`. В нашем примере:
    @@ -128,28 +152,38 @@ function isHidden(elem)
  • `clientTop = 25` -- ширина верхней рамки
- + -Казалось бы, зачем еще какие-то свойства, если ширину рамки можно получить напрямую из CSS? Да, можно. Обычно они действительно не нужны. +...Но на самом деле они -- вовсе не рамки, а отступ внутренней части элемента от внешней. + +В чём же разница? + +Она возникает тогда, когда документ располагается *справа налево* (операционная система на арабском языке или иврите). Полоса прокрутки в этом случае находится слева, и тогда свойство `clientLeft` включает в себя еще и ширину полосы прокрутки. + +Получится так: + + -Но в случае, когда документ располагается *справа налево* (арабский язык, иврит), полоса прокрутки находится слева, и тогда свойство `clientLeft` включает в себя еще и ширину полосы прокрутки. ## clientWidth/Height -Эти свойства -- размер внутренней зоны элемента внутри рамок `border`. +Эти свойства -- размер элемента внутри рамок `border`. -Она включает в себя как ширину содержимого `width`, так и поля `padding`: +Они включают в себя ширину содержимого `width` вместе с полями `padding`, но без прокрутки. - + -Как видно на рисунке выше, `clientWidth` в нашем документе складывается из ширины области содержимого (`284px`) плюс левый и правый `padding` (по `20px`), то есть всего `324px`. +На рисунке выше посмотрим вначале на `clientHeight`, её посчитать проще всего. Прокрутки нет, так что это в точности то, что внутри рамок: CSS-ширина `200px` плюс верхнее и нижнее поля `padding` (по `20px`), итого `240px`. -Аналогично, `clientHeight` -- это высота области содержимого (`200px`) плюс верхний и нижний `padding` (по `20px`), то есть `240px`. На рисунке выше нижний `padding` заполнен текстом, но это неважно: по правилам он всегда входит в `clientHeight`. +На рисунке нижний `padding` заполнен текстом, но это неважно: по правилам он всегда входит в `clientHeight`. + +Теперь `clientWidth` -- ширина содержимого здесь не равна CSS-ширине, её часть "съедает" полоса прокрутки. +Поэтому в `clientWidth` входит не CSS-ширина, а реальная ширина содержимого `284px` плюс левое и правое поля `padding` (по `20px`), итого `324px`. **Если `padding` нет, то `clientWidth/Height` в точности равны размеру области содержимого, внутри рамок и полосы прокрутки.** - + Поэтому в тех случаях, когда мы точно знаем, что `padding` нет, их используют для определения внутренних размеров элемента. @@ -157,17 +191,17 @@ function isHidden(elem) Эти свойства -- аналоги `clientWidth/clientHeight`, но с учетом прокрутки. -Свойства `clientWidth/clientHeight` относятся только к видимой области элемента, а `scrollWidth/scrollHeight` добавляют к ней прокрученную по горизонтали/вертикали. +Свойства `clientWidth/clientHeight` относятся только к видимой области элемента, а `scrollWidth/scrollHeight` добавляют к ней прокрученную (которую не видно) по горизонтали/вертикали. + + На рисунке выше:
    -
  • `scrollHeight = 723` -- полная высота, включая прокрученную область
  • -
  • `scrollWidth = 324` -- полная ширина, включая прокрученную область
  • +
  • `scrollHeight = 723` -- полная внутренняя высота, включая прокрученную область.
  • +
  • `scrollWidth = 324` -- полная внутренняя ширина, в данном случае прокрутки нет, поэтому она равна `clientWidth`.
- - -Эти свойства можно использовать, чтобы "распахнуть" элемент на всю ширину/высоту: +Эти свойства можно использовать, чтобы "распахнуть" элемент на всю ширину/высоту, таким кодом: ```js element.style.height = element.scrollHeight + 'px'; @@ -183,14 +217,13 @@ element.style.height = element.scrollHeight + 'px'; [/pre] [/online] - ## scrollLeft/scrollTop Свойства `scrollLeft/scrollTop` -- ширина/высота невидимой, прокрученной в данный момент, части элемента слева и сверху. Следующее иллюстрация показывает значения `scrollHeight` и `scrollTop` для блока с вертикальной прокруткой. - + [smart header="`scrollLeft/scrollTop` можно изменять"] В отличие от большинства свойств, которые доступны только для чтения, значения `scrollLeft/scrollTop` можно изменить, и браузер выполнит прокрутку элемента. @@ -205,7 +238,9 @@ element.style.height = element.scrollHeight + 'px'; ## Не стоит брать width/height из CSS -Теперь несколько слов о том, как не надо делать. +Мы рассмотрели метрики -- свойства, которые есть у DOM-элементов. Их обычно используют для получения их различных высот, ширин и прочих расстояний. + +Теперь несколько слов о том, как *не* надо делать. Как мы знаем, CSS-высоту и ширину можно установить с помощью `elem.style` и извлечь, используя `getComputedStyle`, которые в подробностях обсуждаются в главе [](/styles-and-classes). @@ -218,11 +253,11 @@ var elem = document.body; alert( getComputedStyle(elem).width ); // вывести CSS-ширину для elem ``` -Всегда ли такой подход сработает? Увы, нет! +Не лучше ли получать ширину так, вместо метрик? Вовсе нет!
    -
  1. Во-первых, CSS-свойства `width/height` зависят от другого свойства -- `box-sizing`, которое определяет, что такое, собственно, эти ширина и высота. Получается, что изменение этого свойства, к примеру, для более удобной вёрстки, может сломать JavaScript.
  2. -
  3. Во-вторых, свойства `width/height` могут быть равны `auto`, например, для инлайн-элемента: +
  4. Во-первых, CSS-свойства `width/height` зависят от другого свойства -- `box-sizing`, которое определяет, что такое, собственно, эти ширина и высота. Получается, что изменение `box-sizing`, к примеру, для более удобной вёрстки, сломает такой JavaScript.
  5. +
  6. Во-вторых, в CSS свойства `width/height` могут быть равны `auto`, например, для инлайн-элемента: ```html @@ -234,48 +269,45 @@ alert( getComputedStyle(elem).width ); // вывести CSS-ширину для */!* ``` + +Конечно, с точки зрения CSS размер `auto` -- совершенно нормально, но нам-то в JavaScript нужен конкретный размер в пикселях, который мы могли бы использовать для вычислений. Получается, что в данном случае ширина `width` из CSS вообще бесполезна.
- -Конечно, с точки зрения CSS размер `auto` -- совершенно нормально, но нам-то в JavaScript нужен конкретный размер в пикселях, который мы могли бы использовать для вычислений. Получается, что в данном случае ширина `width` из CSS вообще бесполезна. - -## Полоса прокрутки и содержимое +Есть и ещё одна причина. Полоса прокрутки -- причина многих проблем и недопониманий. Как говорится, "дьявол кроется в деталях". Недопустимо, чтобы наш код работал на элементах без прокрутки и начинал "глючить" с ней. -При наличии вертикальной полосы прокрутки, она как правило забирает себе место из "области содержимого" элемента. +Как мы говорили ранее, при наличии вертикальной полосы прокрутки, в зависимости от браузера, устройства и операционной системы, она может сдвинуть содержимое. -И это учитывают свойства `clientWidth/clientHeight`. +Получается, что реальная ширина содержимого меньше CSS-ширины. И это учитывают свойства `clientWidth/clientHeight`. -...Но при этом некоторые браузеры отражают реальное уменьшение ширины в результате `getComputedStyle(elem).width`, а некоторые -- нет. - -В примере ниже у элемента с текстом в стилях указано `width:300px`. А вот `getComputedStyle` возвращает значение от `280px` до `300px`, в зависимости от ОС и браузера. +...Но при этом некоторые браузеры также учитывают это в результате `getComputedStyle(elem).width`, то есть возвращают реальную внутреннюю ширину, а некоторые -- именно CSS-свойство. Эти кросс-браузерные отличия -- ещё один повод не использовать такой подход, а использовать свойства-метрики. [online] -Если ваш браузер в принципе показывает полосу прокрутки (например, под Windows почти все браузеры так делают), то вы можете протестировать это сами, нажав на кнопку в ифрейме ниже: -[/online] +Если ваш браузер показывает полосу прокрутки (например, под Windows почти все браузеры так делают), то вы можете протестировать это сами, нажав на кнопку в ифрейме ниже. [iframe src="cssWidthScroll" link border=1] -Описанные разночтения касаются только чтения свойства `getComputedStyle(...).width` из JavaScript, визуальное отображение корректно в обоих случаях -- ширина текста при наличии прокрутки в обоих случаях уменьшается. +У элемента с текстом в стилях указано `width:300px`. -Этот пример важен, чтобы ещё лучше понять: CSS-свойство `width` не следует использовать в JavaScript. А стоит использовать метрики, которые мы разобрали в этом разделе. +На момент написания этой главы при тестировании в Chrome под Windows `alert` выводил `283px`, а в Firefox -- `300px`. При этом оба браузера показывали прокрутку. Это из-за того, что Firefox возвращал именно CSS-ширину, а Chrome -- реальную ширину, за вычетом прокрутки. +[/online] +Описанные разночтения касаются только чтения свойства `getComputedStyle(...).width` из JavaScript, визуальное отображение корректно в обоих случаях. ## Итого У элементов есть следующие метрики:
    -
  • `clientWidth/clientHeight` -- ширина/высота видимой области, включая поля, но не полосы прокрутки.
  • -
  • `clientLeft/clientTop` -- ширина левой/верхней рамки или, точнее, сдвиг клиентской области, относительно верхнего левого угла блока. -Используется, преимущественно, в IE<8 для вычисления сдвига `document.body`. -
  • -
  • `scrollWidth/scrollHeight` -- ширина/высота прокручиваемой области. Включает в себя `padding` и не включает полосы прокрутки.
  • -
  • `scrollLeft/scrollTop` -- ширина/высота прокрученной части документа, считается от верхнего левого угла.
  • -
  • `offsetWidth/offsetHeight` -- "внешняя" ширина/высота блока, не считая отступов.
  • `offsetParent` -- "родитель по дереву рендеринга" -- ближайшая ячейка таблицы, body для статического позиционирования или ближайший позиционированный элемент для других типов позиционирования.
  • `offsetLeft/offsetTop` -- позиция в пикселях левого верхнего угла блока, относительно его `offsetParent`.
  • +
  • `offsetWidth/offsetHeight` -- "внешняя" ширина/высота блока, включая рамки.
  • +
  • `clientLeft/clientTop` -- отступ области содержимого от левого-верхнего угла элемента. Если операционная система располагает вертикальную прокрутку справа, то равны ширинам левой/верхней рамки, если же слева (ОС на иврите, арабском), то `clientLeft` включает в себя прокрутку. +
  • +
  • `clientWidth/clientHeight` -- ширина/высота содержимого вместе с полями `padding`, но без полосы прокрутки.
  • +
  • `scrollWidth/scrollHeight` -- ширина/высота содержимого, включая прокручиваемую область. Включает в себя `padding` и не включает полосы прокрутки.
  • +
  • `scrollLeft/scrollTop` -- ширина/высота прокрученной части документа, считается от верхнего левого угла.
Все свойства, доступны только для чтения, кроме `scrollLeft/scrollTop`. Изменение этих свойств заставляет браузер прокручивать элемент. diff --git a/2-ui/1-document/15-metrics/cssWidthScroll.view/index.html b/2-ui/1-document/15-metrics/cssWidthScroll.view/index.html index 27019b13..bf4f7925 100755 --- a/2-ui/1-document/15-metrics/cssWidthScroll.view/index.html +++ b/2-ui/1-document/15-metrics/cssWidthScroll.view/index.html @@ -13,17 +13,12 @@
У элемента стоит style="width:300px"
- + diff --git a/2-ui/1-document/15-metrics/metric-client-left-top-rtl.png b/2-ui/1-document/15-metrics/metric-client-left-top-rtl.png new file mode 100644 index 00000000..e7f56264 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-left-top-rtl.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-left-top-rtl@2x.png b/2-ui/1-document/15-metrics/metric-client-left-top-rtl@2x.png new file mode 100644 index 00000000..c4e8a226 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-left-top-rtl@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-left-top.png b/2-ui/1-document/15-metrics/metric-client-left-top.png new file mode 100644 index 00000000..4d384490 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-left-top.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-left-top@2x.png b/2-ui/1-document/15-metrics/metric-client-left-top@2x.png new file mode 100644 index 00000000..b78fc0b0 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-left-top@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-width-height.png b/2-ui/1-document/15-metrics/metric-client-width-height.png new file mode 100644 index 00000000..3294dfa9 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-width-height.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-width-height@2x.png b/2-ui/1-document/15-metrics/metric-client-width-height@2x.png new file mode 100644 index 00000000..82dfe3a1 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-width-height@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-width-nopadding.png b/2-ui/1-document/15-metrics/metric-client-width-nopadding.png new file mode 100644 index 00000000..55aa066a Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-width-nopadding.png differ diff --git a/2-ui/1-document/15-metrics/metric-client-width-nopadding@2x.png b/2-ui/1-document/15-metrics/metric-client-width-nopadding@2x.png new file mode 100644 index 00000000..076d05e5 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-client-width-nopadding@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-css.png b/2-ui/1-document/15-metrics/metric-css.png new file mode 100644 index 00000000..b82f0182 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-css.png differ diff --git a/2-ui/1-document/15-metrics/metric-css@2x.png b/2-ui/1-document/15-metrics/metric-css@2x.png new file mode 100644 index 00000000..2bde2d0c Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-css@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-offset-parent.png b/2-ui/1-document/15-metrics/metric-offset-parent.png new file mode 100644 index 00000000..450d587e Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-offset-parent.png differ diff --git a/2-ui/1-document/15-metrics/metric-offset-width-height.png b/2-ui/1-document/15-metrics/metric-offset-width-height.png new file mode 100644 index 00000000..cbcff9fd Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-offset-width-height.png differ diff --git a/2-ui/1-document/15-metrics/metric-offset-width-height@2x.png b/2-ui/1-document/15-metrics/metric-offset-width-height@2x.png new file mode 100644 index 00000000..00bde81f Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-offset-width-height@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-scroll-top.png b/2-ui/1-document/15-metrics/metric-scroll-top.png new file mode 100644 index 00000000..379fdeba Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-scroll-top.png differ diff --git a/2-ui/1-document/15-metrics/metric-scroll-top@2x.png b/2-ui/1-document/15-metrics/metric-scroll-top@2x.png new file mode 100644 index 00000000..21f3fd95 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-scroll-top@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric-scroll-width-height.png b/2-ui/1-document/15-metrics/metric-scroll-width-height.png new file mode 100644 index 00000000..75fdda43 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-scroll-width-height.png differ diff --git a/2-ui/1-document/15-metrics/metric-scroll-width-height@2x.png b/2-ui/1-document/15-metrics/metric-scroll-width-height@2x.png new file mode 100644 index 00000000..b7a55a32 Binary files /dev/null and b/2-ui/1-document/15-metrics/metric-scroll-width-height@2x.png differ diff --git a/2-ui/1-document/15-metrics/metric.view/index.html b/2-ui/1-document/15-metrics/metric.view/index.html index 50972d9c..85d99068 100755 --- a/2-ui/1-document/15-metrics/metric.view/index.html +++ b/2-ui/1-document/15-metrics/metric.view/index.html @@ -13,9 +13,8 @@ width: 300px; height: 200px; overflow: auto; - border: 25px solid #F0E68C; + border: 25px solid #E8C48F; padding: 20px; - margin: 20px; } .key { cursor: pointer; @@ -29,9 +28,7 @@

Introduction

-

This Ecma Standard is based on several originating technologies, the most well known being JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan Eich at Netscape and first appeared in that company's Navigator 2.0 browser. It has appeared in all subsequent browsers from Netscape and in all browsers from Microsoft starting with Internet Explorer 3.0.

- -

The development of this Standard started in November 1996. The first edition of this Ecma Standard was adopted by the Ecma General Assembly of June 1997.

+

This Ecma Standard is based on several originating technologies, the most well known being JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan Eich at Netscape and first appeared in that company's Navigator 2.0 browser. It has appeared in all subsequent browsers from Netscape and in all browsers from Microsoft starting with Internet Explorer 3.0. The development of this Standard started in November 1996. The first edition of this Ecma Standard was adopted by the Ecma General Assembly of June 1997.

That Ecma Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262, in April 1998. The Ecma General Assembly of June 1998 approved the second edition of ECMA-262 to keep it fully aligned with ISO/IEC 16262. Changes between the first and the second edition are editorial in nature.

diff --git a/2-ui/1-document/16-metrics-window/document-client-width-height.svg b/2-ui/1-document/16-metrics-window/document-client-width-height.svg index 963f22a7..cb9f6b69 100644 --- a/2-ui/1-document/16-metrics-window/document-client-width-height.svg +++ b/2-ui/1-document/16-metrics-window/document-client-width-height.svg @@ -1,24 +1,27 @@ - + + + document-client-width-height.svg + Created with bin/sketchtool. - - - - - - - - - - - + + + + + + + + + + + - - - + + + documentElement.clientHeight - + document.documentElement.clientWidth diff --git a/2-ui/1-document/17-coordinates/coords.svg b/2-ui/1-document/17-coordinates/coords.svg index 02563c63..11d5337a 100644 --- a/2-ui/1-document/17-coordinates/coords.svg +++ b/2-ui/1-document/17-coordinates/coords.svg @@ -1,33 +1,36 @@ - + + + coords.svg + Created with bin/sketchtool. - - - - - - - - + + + + + + + + - - - - - - + + + + + + <DIV> - + top - + bottom - + left - + right diff --git a/2-ui/1-document/4-traversing-dom/dom-links-elements.svg b/2-ui/1-document/4-traversing-dom/dom-links-elements.svg index c5bbcf77..0cbbba30 100644 --- a/2-ui/1-document/4-traversing-dom/dom-links-elements.svg +++ b/2-ui/1-document/4-traversing-dom/dom-links-elements.svg @@ -1,55 +1,58 @@ - + + + dom-links-elements.svg + Created with bin/sketchtool. - - - + + + document.documentElement <HTML> - + document.body (если внутри body) - + - - - + + + parent Element - - - - + + + + <DIV> - + - + - + next Element Sibling - + - + previous Element Sibling - - - + + + children - + first Element Child - + last Element Child diff --git a/2-ui/1-document/4-traversing-dom/dom-links.svg b/2-ui/1-document/4-traversing-dom/dom-links.svg index 93b829b5..f05fbf85 100644 --- a/2-ui/1-document/4-traversing-dom/dom-links.svg +++ b/2-ui/1-document/4-traversing-dom/dom-links.svg @@ -1,54 +1,57 @@ - + + + dom-links.svg + Created with bin/sketchtool. - - - + + + document - + document.documentElement <HTML> - + document.body (если внутри body) - + - - + + - - + + parentNode - - - - - + + + + + <DIV> - + - + - + nextSibling - + - + previousSibling - - - + + + childNodes - + firstChild - + lastChild diff --git a/figures.sketch b/figures.sketch index 4bf7704d..7f5b5fe9 100644 Binary files a/figures.sketch and b/figures.sketch differ