Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Coordinates#305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
MykolaSopiha merged 22 commits intojavascript-tutorial:masterfromjeneg:2-1-11
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
22 commits
Select commitHold shift + click to select a range
5e13240
# Coordinates
jenegFeb 1, 2022
a22a9ca
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
6535781
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
8f8867f
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
281591f
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
f7ad8e1
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
98c44c0
Update 2-ui/1-document/11-coordinates/2-position-at/task.md
MykolaSopihaFeb 6, 2022
617ff86
Update 2-ui/1-document/11-coordinates/2-position-at/source.view/index…
MykolaSopihaFeb 6, 2022
df9d7fa
Update 2-ui/1-document/11-coordinates/2-position-at/solution.view/ind…
MykolaSopihaFeb 6, 2022
412358f
Update 2-ui/1-document/11-coordinates/2-position-at/solution.md
MykolaSopihaFeb 6, 2022
2df5646
Update 2-ui/1-document/11-coordinates/1-find-point-coordinates/soluti…
MykolaSopihaFeb 6, 2022
ec310ec
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
19f81c1
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
1bc5be1
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
37c5c56
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
36b6c29
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
883e112
Update 2-ui/1-document/11-coordinates/1-find-point-coordinates/soluti…
MykolaSopihaFeb 6, 2022
1461da8
Update 2-ui/1-document/11-coordinates/1-find-point-coordinates/source…
MykolaSopihaFeb 6, 2022
33a1d72
Update 2-ui/1-document/11-coordinates/4-position-inside-absolute/task.md
MykolaSopihaFeb 6, 2022
364fa27
Update 2-ui/1-document/11-coordinates/3-position-at-absolute/task.md
MykolaSopihaFeb 6, 2022
6f6e06e
Update 2-ui/1-document/11-coordinates/3-position-at-absolute/solution.md
MykolaSopihaFeb 6, 2022
bdc05a1
Update 2-ui/1-document/11-coordinates/article.md
MykolaSopihaFeb 6, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
#Outer corners
#Зовнішні кути

Outer corners are basically what we get from [elem.getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect).
Зовнішні кути -- це саме те, що ми отримуємо в результаті виклику [elem.getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect).

Coordinates of the upper-left corner`answer1`and the bottom-right corner `answer2`:
Координати верхнього лівого кута`answer1`і нижнього правого кута `answer2`:

```js
let coords = elem.getBoundingClientRect();
Expand All@@ -11,19 +11,19 @@ let answer1 = [coords.left, coords.top];
let answer2 = [coords.right, coords.bottom];
```

#Left-upper inner corner
#Лівий верхній внутрішній кут

That differs from the outer corner by the border width. A reliable way to get the distance is `clientLeft/clientTop`:
Координати внутрішнього кута відрізняється від зовнішнього на ширину рамки. Надійним способом їх отримання є використання `clientLeft/clientTop`:

```js
let answer3 = [coords.left + field.clientLeft, coords.top + field.clientTop];
```

#Right-bottom inner corner
#Правий нижній внутрішній кут

In our case we need to substract the border size from the outer coordinates.
У нашому випадку нам потрібно відняти розмір рамки від зовнішніх координат.

We could useCSSway:
Можемо використатиCSSвластивості:

```js
let answer4 = [
Expand All@@ -32,7 +32,7 @@ let answer4 = [
];
```

An alternative way would be to add`clientWidth/clientHeight`to coordinates of the left-upper corner. That's probably even better:
Альтернативним способом було б додавання`clientWidth/clientHeight`до координат лівого верхнього кута. Це, мабуть, навіть краще:

```js
let answer4 = [
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,18 +5,18 @@
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<script>
document.onclick = function(e) { //shows click coordinates
document.onclick = function(e) { //показує координати кліку
coords.innerHTML = e.clientX + ':' + e.clientY;
};
</script>
</head>

<body>

Click anywhere to get window coordinates.
<br>That's for testing, to check the result you get by JavaScript.
Клацніть будь-де, щоб отримати координати вікна.
<br>Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
<br>
<div id="coords">(click coordinates show up here)</div>
<div id="coords">(координати кліку з’являться тут)</div>


<div id="field">
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,18 +5,18 @@
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<script>
document.onclick = function(e) { //shows click coordinates
document.onclick = function(e) { //показує координати кліку
coords.innerHTML = e.clientX + ':' + e.clientY;
};
</script>
</head>

<body>

Click anywhere to get window coordinates.
<br>That's for testing, to check the result you get by JavaScript.
Клацніть будь-де, щоб отримати координати вікна.
<br>Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
<br>
<div id="coords">(click coordinates show up here)</div>
<div id="coords">(координати кліку з’являться тут)</div>


<div id="field">
Expand All@@ -32,7 +32,7 @@


<script>
// ...your code...
// ...ваш код...
</script>

</body>
Expand Down
24 changes: 12 additions & 12 deletions2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
importance: 5
важливість: 5

---

#Find window coordinates of the field
#Знайти координати поля відносно вікна

In theiframebelow you can see a document with the green "field".
Уiframeнижче ви можете побачити документ із зеленим «полем».

Use JavaScript to find window coordinates of corners pointed by with arrows.
Використовуючи JavaScript, знайдіть координати кутів відносно вікна, на які вказано стрілками.

There's a small feature implemented in the document for convenience. A click at any place shows coordinates there.
Для зручності в документі реалізована невелика функція, яка показує координати кліку.

[iframe border=1 height=360 src="source" link edit]

Your code should use DOMto get window coordinates of:
Ваш код повинен використовувати DOMдля отримання чотирьох пар координат відносно вікна:

1.Upper-left, outer corner (that's simple).
2.Bottom-right, outer corner (simple too).
3.Upper-left, inner corner (a bit harder).
4.Bottom-right, inner corner (there are several ways, choose one).
1.Верхній лівий, зовнішній кут (це просто).
2.Правий нижній, зовнішній кут (теж просто).
3.Верхній лівий, внутрішній кут (трохи складніше).
4.Правий нижній, внутрішній кут (є кілька способів, оберіть один).

The coordinates that you calculate should be the same as those returned by the mouse click.
Обчислені координати повинні збігатися з тими, які повертаються клацанням миші.

P.S.The code should also work if the element has another size or border, not bound to any fixed values.
P.S.Код також повинен працювати, якщо елемент має інший розмір або рамку, тобто не прив’язаний до жодних фіксованих значень.
6 changes: 3 additions & 3 deletions2-ui/1-document/11-coordinates/2-position-at/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
In this task we only need to accurately calculate the coordinates. See the code for details.
У цьому завданні нам потрібно лише точно розрахувати координати. Подробиці дивіться в коді.

Please note: the elements must be in the document to read`offsetHeight`and other properties.
A hidden (`display:none`)or out of the document element has no size.
Зверніть увагу: елементи повинні бути в документі, щоб прочитати`offsetHeight`та інші властивості.
Прихований елемент (`display:none`)або елемент поза документом не має розміру.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand All@@ -24,13 +24,13 @@

<script>
/**
*Positionselemrelative to anchoras said in position.
*Розміщує елементelemвідносно елемента anchorтак, як зазначено в положенні position.
*
* @param {Node} anchorAnchor element for positioning
* @param {string} positionOne of: top/right/bottom
* @param {Node} elemElement to position
* @param {Node} anchorЕлемент, відносно якого позиціонується елемент elem
* @param {string} positionОдин з: top/right/bottom
* @param {Node} elemЕлемент, який позиціонується
*
*Both elements: elemand anchormust be in the document
*Обидва елементи: elemі anchorповинні бути в документі
*/
function positionAt(anchor, position, elem) {

Expand All@@ -56,8 +56,8 @@
}

/**
*Shows a note with the given html at the given position
*relative to theanchor element.
*Показує примітку із заданим HTML у заданій позиції
*відносно елементаanchor.
*/
function showNote(anchor, position, html) {

Expand All@@ -69,7 +69,7 @@
positionAt(anchor, position, note);
}

//test it
//спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand All@@ -24,21 +24,21 @@

<script>
/**
*Positionselemrelative to anchoras said in position.
*Розміщує елементelemвідносно елемента anchorтак, як зазначено в положенні position.
*
* @param {Node} anchorAnchor element for positioning
* @param {string} positionOne of: top/right/bottom
* @param {Node} elemElement to position
* @param {Node} anchorЕлемент, відносно якого позиціонується елемент elem
* @param {string} positionОдин з: top/right/bottom
* @param {Node} elemЕлемент, який позиціонується
*
*Both elements: elemand anchormust be in the document
*Обидва елементи: elemі anchorповинні бути в документі
*/
function positionAt(anchor, position, elem) {
// ...your code ...
// ...ваш код ...
}

/**
*Shows a note with the given html at the given position
*relative to theanchor element.
*Показує примітку із заданим HTML у заданій позиції
*відносно елементаanchor.
*/
function showNote(anchor, position, html) {

Expand All@@ -50,7 +50,7 @@
positionAt(anchor, position, note);
}

//test it
//спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down
18 changes: 9 additions & 9 deletions2-ui/1-document/11-coordinates/2-position-at/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
importance: 5
важливість: 5

---

#Show a note near the element
#Покажіть примітку біля елемента

Create a function`positionAt(anchor, position, elem)` that positions `elem`, depending on `position`near`anchor` element.
Створіть функцію`positionAt(anchor, position, elem)`, яка позиціонує `elem` залежно від `position`біля елемента`anchor`.

The `position`must be a string with any one of 3 values:
- `"top"` -position `elem`right above `anchor`
- `"right"` -position `elem`immediately at the right of `anchor`
- `"bottom"` -position `elem`right below `anchor`
Аргумент `position`має бути рядком з будь-яким із 3 значень:
- `"top"` -розмістити `elem`праворуч над `anchor`
- `"right"` -розмістити `elem`безпосередньо праворуч від `anchor`
- `"bottom"` -розмістити `elem`прямо під `anchor`

It's used inside function `showNote(anchor, position, html)`,provided in the task source code, that creates a "note" element with given`html`and shows it at the given `position`near the `anchor`.
Аргумент використовується всередині функції `showNote(anchor, position, html)`,наданої у вихідному коді завдання, який створює елемент примітки із заданим`html`і показує його у заданій позиції `position`біля елементу `anchor`.

Here's the demo of notes:
Ось демонстрація приміток:

[iframe src="solution" height="350" border="1" link]
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
The solution is actually pretty simple:
Рішення насправді досить просте:

-Use `position:absolute`in CSSinstead of`position:fixed`for `.note`.
-Use the function[getCoords()](info:coordinates#getCoords)from the chapter<info:coordinates> to get document-relative coordinates.
-Використовуйте `position:absolute`у CSSзамість`position:fixed`для елемента `.note`.
-Використовуйте функцію[getCoords()](info:coordinates#getCoords)з розділу<info:coordinates>, щоб отримати координати відносно документа.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand DownExpand Up@@ -66,7 +66,7 @@
positionAt(anchor, position, note);
}

//test it
//спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
importance: 5
важливість: 5

---

#Show a note near the element (absolute)
#Покажіть примітку біля елемента (абсолютне позиціювання)

Modify the solution of the [previous task](info:task/position-at) so that the note uses`position:absolute`instead of `position:fixed`.
Скорегуйте рішення [попереднього завдання](info:task/position-at), щоб для позиціювання примітки використовувалася властивість`position:absolute`замість `position:fixed`.

That will prevent its "runaway" from the element when the page scrolls.
Це запобіжить «втечу» нотатки від елемента під час прокручування сторінки.

Take the solution of that task as a starting point. To test the scroll, add the style `<body style="height: 2000px">`.
Візьміть розв’язання попереднього завдання за відправну точку. Щоб перевірити прокрутку, додайте стиль `<body style="height: 2000px">`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
importance: 5
важливість: 5

---

#Position the note inside (absolute)
#Розташуйте примітку всередині елемента (абсолютне позиціювання)

Extend the previous task<info:task/position-at-absolute>:teach the function`positionAt(anchor, position, elem)`to insert`elem`inside the `anchor`.
Розширте попереднє завдання<info:task/position-at-absolute>:навчіть функцію`positionAt(anchor, position, elem)`вставляти`elem`всередині `anchor`.

New values for `position`:
Нові значення для `position`:

- `top-out`, `right-out`, `bottom-out` --work the same as before, they insert the`elem`over/right/under `anchor`.
- `top-in`, `right-in`, `bottom-in` --insert `elem`inside the `anchor`: stick it to the upper/right/bottom edge.
- `top-out`, `right-out`, `bottom-out` --працюють так само як і раніше, вони вставляють`elem`над/праворуч/під елементом `anchor`.
- `top-in`, `right-in`, `bottom-in` --вставляють `elem`всередину елемента `anchor`, та прикріпляють його до верхнього/правого/нижнього краю.

For instance:
Наприклад:

```js
//shows the note above blockquote
//показує примітку над елементом blockquote
positionAt(blockquote, "top-out", note);

//shows the note inside blockquote, at the top
//показує примітку всередині елемента blockquote поряд з верхнім краєм
positionAt(blockquote, "top-in", note);
```

The result:
Результат:

[iframe src="solution" height="310" border="1" link]

As the source code, take the solution of the task <info:task/position-at-absolute>.
Для початку візьміть розв’язання задачі <info:task/position-at-absolute>.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp