- Notifications
You must be signed in to change notification settings - Fork179
Introduction to browser events#292
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
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
a11e2a3
d073b92
6f63dff
690516f
d1d20f9
126b55b
1808c2f
b7f4746
c31ff51
68d53eb
019602e
550b1fb
787568b
82f0f9a
cbda1c0
3f73a4b
007d5ac
0a58cb5
15efbc0
7758975
ca0c3b0
86fccb4
1ea7283
676d942
eff8fea
5cb6b18
4a1c393
c987f1d
b5a26f7
163d7e6
3063331
ca8f7bb
4684a0d
9266f24
3b740f2
bda1c77
5777c31
599737f
cdf34ab
bee8302
8e473d3
d5f632e
c0286d4
e1ae78c
2397c96
ef0bd68
2c446c1
b3cabe4
9321de2
5ac3d87
23c6012
a092cc6
8d4eba5
7f57848
f73b996
712918a
89acea9
53a2b30
6d97cea
9efb2eb
f4bb145
dc40c13
caef75f
274b155
2605ab6
7da7a93
dbf1f1b
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
Можемо використати `this`в обробнику для доступу до самого елемента: | ||
```html run height=50 | ||
<input type="button" onclick="this.hidden=true" value="Сховати"> | ||
``` |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,8 +1,8 @@ | ||||||
Відповідь: `1`і `2`. | ||||||
Перший обробник спрацює, тому що він не був вилучений методом`removeEventListener`.Щоб видалити обробник, необхідно передати саме ту функцію, яка була призначена як обробник. Попри те, що код ідентичний, в `removeEventListener` передається нова, інша функція. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
Щоб видалити функцію-обробник, потрібно десь зберегти посилання на неї, наприклад: | ||||||
```js | ||||||
function handler() { | ||||||
@@ -13,4 +13,4 @@ button.addEventListener("click", handler); | ||||||
button.removeEventListener("click", handler); | ||||||
``` | ||||||
Обробник`button.onclick`спрацює все одно. Разом з `addEventListener`. |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,12 +1,12 @@ | ||||||
важливість: 5 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
--- | ||||||
#Який обробник запуститься? | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
У змінній `button` знаходиться кнопка. Спочатку на ній немає обробників. | ||||||
Який з обробників запуститься? Що буде виведено під час кліку після виконання коду? | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
```js no-beautify | ||||||
button.addEventListener("click", () => alert("1")); | ||||||
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,11 +1,11 @@ | ||||||
Спочатку ми маємо вибрати метод позиціювання м’яча. | ||||||
Ми не можемо використати`position:fixed`для цього, оскільки прокручування сторінки переміщатиме м’яч поля. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
Правильніше використовувати`position:absolute`і, щоб зробити позиціювання справді надійним, зробимо саме поле`field`позиціонованим. | ||||||
Тоді м’яч буде позиціонований щодо поля: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
```css | ||||||
#field { | ||||||
@@ -16,36 +16,36 @@ Then the ball will be positioned relatively to the field: | ||||||
#ball { | ||||||
position: absolute; | ||||||
left: 0; /*по відношенню до найближчого розташованого предка (field) */ | ||||||
top: 0; | ||||||
transition: 1s all; /* CSS-анімація для значень left/topробить пересування м’яча плавним */ | ||||||
} | ||||||
``` | ||||||
Далі ми маємо призначити коректні значення`ball.style.left/top`.Зараз вони містять координати щодо поля. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
Здається, що так краще, як вважаєте? | ||||||
Як на зображенні: | ||||||
 | ||||||
Ми маємо `event.clientX/clientY` --координати натискання мишки щодо вікна браузера. | ||||||
Щоб отримати значення `left`для м’яча після натискання мишки щодо поля, ми повинні від координати натискання мишки відняти координату лівого краю поля та ширину межі: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
```js | ||||||
let left = event.clientX - fieldCoords.left - field.clientLeft; | ||||||
``` | ||||||
Значення `ball.style.left`означає «лівий край елемента» (м’яча).І якщо ми призначимо такий `left` для м’яча, то його ліва межа, а не центр, буде під курсором миші. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
Нам потрібно зрушити м'яч на половину його висоти вгору та половину його ширини вліво, щоб центр м’яча точно збігався з точкою натискання мишки. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
У результаті значення для`left`буде таким: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
```js | ||||||
let left = event.clientX - fieldCoords.left - field.clientLeft - ball.offsetWidth/2; | ||||||
``` | ||||||
Вертикальна координата обчислюватиметься за тією ж логікою. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
Слід пам’ятати, що ширина та висота м’яча має бути відома в той момент, коли ми отримуємо значення`ball.offsetWidth`.Це значення може бути задано вHTMLабо CSS. |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -27,7 +27,7 @@ | ||||||
<body style="height:2000px"> | ||||||
Натисніть поле, щоб перемістити м’яч. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
<br> | ||||||
@@ -39,29 +39,29 @@ | ||||||
<script> | ||||||
field.onclick = function(event) { | ||||||
//координати поля щодо вікна браузера | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
let fieldCoords = this.getBoundingClientRect(); | ||||||
//м’яч має абсолютне позиціювання (position:absolute), поле -- відносне (position:relative) | ||||||
//таким чином, координати м’яча розраховуються відносно внутрішнього, верхнього лівого кута поля. | ||||||
let ballCoords = { | ||||||
top: event.clientY - fieldCoords.top - field.clientTop - ball.clientHeight / 2, | ||||||
left: event.clientX - fieldCoords.left - field.clientLeft - ball.clientWidth / 2 | ||||||
}; | ||||||
//забороняємо перетинати верхню межу поля | ||||||
if (ballCoords.top < 0) ballCoords.top = 0; | ||||||
//забороняємо перетинати ліву межу поля | ||||||
if (ballCoords.left < 0) ballCoords.left = 0; | ||||||
//забороняємо перетинати праву межу поля | ||||||
if (ballCoords.left + ball.clientWidth > field.clientWidth) { | ||||||
ballCoords.left = field.clientWidth - ball.clientWidth; | ||||||
} | ||||||
//забороняємо перетинати нижню межу поля | ||||||
if (ballCoords.top + ball.clientHeight > field.clientHeight) { | ||||||
ballCoords.top = field.clientHeight - ball.clientHeight; | ||||||
} | ||||||
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,12 +1,12 @@ | ||||||
Щоб додати кнопку закриття, ми можемо використовувати або `position:absolute` (і зробити плитку (pane) `position:relative`)або `float:right`.Перевага варіанта з`float:right`у тому, що кнопка закриття ніколи не перекриє текст, але варіант`position:absolute`дає більше свободи для дій. Загалом вибір за вами. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Suggested change
| ||||||
Тоді для кожного повідомлення(pane) код може бути таким: | ||||||
```js | ||||||
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>'); | ||||||
``` | ||||||
Елемент`<button>`стає `pane.firstChild`,таким чином ми можемо додати до нього обробник події: | ||||||
```js | ||||||
pane.firstChild.onclick = () => pane.remove(); | ||||||
Uh oh!
There was an error while loading.Please reload this page.