From de630426a538c1f77d7c59e66827cb75693ed95b Mon Sep 17 00:00:00 2001 From: MDN Date: Wed, 21 Apr 2021 00:11:44 +0000 Subject: [CRON] sync translated content --- files/bn/_redirects.txt | 6 + files/bn/_wikihistory.json | 12 +- files/bn/orphaned/web/guide/events/index.html | 38 +++ files/bn/web/guide/events/index.html | 37 --- files/de/_redirects.txt | 1 + files/de/_wikihistory.json | 14 +- files/de/orphaned/web/guide/events/index.html | 54 ++++ files/de/web/guide/events/index.html | 53 ---- files/es/_redirects.txt | 15 +- files/es/_wikihistory.json | 68 ++--- .../api/detecting_device_orientation/index.html | 279 ++++++++++++++++++ .../api/document_object_model/events/index.html | 73 +++++ .../web/guide/events/event_handlers/index.html | 133 +++++++++ files/es/orphaned/web/guide/events/index.html | 17 ++ .../index.html | 48 ++++ .../api/detecting_device_orientation/index.html | 278 ------------------ .../api/document_object_model/events/index.html | 73 ----- .../es/web/guide/events/event_handlers/index.html | 133 --------- files/es/web/guide/events/index.html | 17 -- .../index.html | 49 ---- files/fi/_redirects.txt | 6 + files/fi/_wikihistory.json | 12 +- files/fi/orphaned/web/guide/events/index.html | 54 ++++ files/fi/web/guide/events/index.html | 53 ---- files/fr/_redirects.txt | 12 +- files/fr/_wikihistory.json | 62 ++-- .../api/detecting_device_orientation/index.html | 220 ++++++++++++++ .../api/document_object_model/events/index.html | 75 +++++ files/fr/orphaned/web/guide/events/index.html | 19 ++ .../index.html | 77 +++++ .../api/detecting_device_orientation/index.html | 220 -------------- .../api/document_object_model/events/index.html | 75 ----- files/fr/web/guide/events/index.html | 19 -- .../index.html | 77 ----- files/ja/_redirects.txt | 14 +- files/ja/_wikihistory.json | 94 +++--- .../api/detecting_device_orientation/index.html | 229 +++++++++++++++ .../api/document_object_model/events/index.html | 89 ++++++ .../web/guide/events/event_handlers/index.html | 173 +++++++++++ files/ja/orphaned/web/guide/events/index.html | 51 ++++ .../index.html | 50 ++++ .../overview_of_events_and_handlers/index.html | 137 +++++++++ .../api/detecting_device_orientation/index.html | 228 --------------- .../api/document_object_model/events/index.html | 88 ------ .../ja/web/guide/events/event_handlers/index.html | 172 ----------- files/ja/web/guide/events/index.html | 50 ---- .../index.html | 49 ---- .../overview_of_events_and_handlers/index.html | 136 --------- files/ko/_redirects.txt | 6 +- files/ko/_wikihistory.json | 52 ++-- .../api/detecting_device_orientation/index.html | 274 ++++++++++++++++++ .../api/document_object_model/events/index.html | 85 ++++++ files/ko/orphaned/web/guide/events/index.html | 52 ++++ .../overview_of_events_and_handlers/index.html | 143 +++++++++ .../api/detecting_device_orientation/index.html | 274 ------------------ .../api/document_object_model/events/index.html | 84 ------ files/ko/web/guide/events/index.html | 51 ---- .../overview_of_events_and_handlers/index.html | 142 --------- files/pt-br/_redirects.txt | 6 +- files/pt-br/_wikihistory.json | 48 ++-- .../api/document_object_model/events/index.html | 83 ++++++ .../web/guide/events/event_handlers/index.html | 165 +++++++++++ files/pt-br/orphaned/web/guide/events/index.html | 37 +++ .../overview_of_events_and_handlers/index.html | 133 +++++++++ .../api/document_object_model/events/index.html | 83 ------ .../web/guide/events/event_handlers/index.html | 164 ----------- files/pt-br/web/guide/events/index.html | 36 --- .../overview_of_events_and_handlers/index.html | 132 --------- files/pt-pt/_redirects.txt | 3 +- files/pt-pt/_wikihistory.json | 12 +- files/pt-pt/orphaned/web/guide/events/index.html | 134 +++++++++ files/pt-pt/web/guide/events/index.html | 134 --------- files/ru/_redirects.txt | 6 +- files/ru/_wikihistory.json | 58 ++-- .../api/document_object_model/events/index.html | 81 ++++++ .../web/guide/events/event_handlers/index.html | 167 +++++++++++ files/ru/orphaned/web/guide/events/index.html | 60 ++++ .../overview_of_events_and_handlers/index.html | 131 +++++++++ .../api/document_object_model/events/index.html | 81 ------ .../ru/web/guide/events/event_handlers/index.html | 166 ----------- files/ru/web/guide/events/index.html | 59 ---- .../overview_of_events_and_handlers/index.html | 130 --------- files/zh-cn/_redirects.txt | 10 +- files/zh-cn/_wikihistory.json | 110 +++---- .../api/detecting_device_orientation/index.html | 319 +++++++++++++++++++++ .../api/document_object_model/events/index.html | 81 ++++++ .../web/guide/events/event_handlers/index.html | 181 ++++++++++++ files/zh-cn/orphaned/web/guide/events/index.html | 55 ++++ .../index.html | 45 +++ .../overview_of_events_and_handlers/index.html | 136 +++++++++ .../api/detecting_device_orientation/index.html | 318 -------------------- .../api/document_object_model/events/index.html | 80 ------ .../web/guide/events/event_handlers/index.html | 180 ------------ files/zh-cn/web/guide/events/index.html | 54 ---- .../index.html | 44 --- .../overview_of_events_and_handlers/index.html | 135 --------- files/zh-tw/_redirects.txt | 8 +- files/zh-tw/_wikihistory.json | 54 ++-- .../api/detecting_device_orientation/index.html | 279 ++++++++++++++++++ .../api/document_object_model/events/index.html | 70 +++++ .../web/guide/events/event_handlers/index.html | 179 ++++++++++++ files/zh-tw/orphaned/web/guide/events/index.html | 53 ++++ .../api/detecting_device_orientation/index.html | 278 ------------------ .../api/document_object_model/events/index.html | 70 ----- .../web/guide/events/event_handlers/index.html | 178 ------------ files/zh-tw/web/guide/events/index.html | 52 ---- 106 files changed, 5129 insertions(+), 5051 deletions(-) create mode 100644 files/bn/orphaned/web/guide/events/index.html delete mode 100644 files/bn/web/guide/events/index.html create mode 100644 files/de/orphaned/web/guide/events/index.html delete mode 100644 files/de/web/guide/events/index.html create mode 100644 files/es/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/es/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/es/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/es/orphaned/web/guide/events/index.html create mode 100644 files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/es/web/api/detecting_device_orientation/index.html delete mode 100644 files/es/web/api/document_object_model/events/index.html delete mode 100644 files/es/web/guide/events/event_handlers/index.html delete mode 100644 files/es/web/guide/events/index.html delete mode 100644 files/es/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/fi/orphaned/web/guide/events/index.html delete mode 100644 files/fi/web/guide/events/index.html create mode 100644 files/fr/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/fr/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/fr/orphaned/web/guide/events/index.html create mode 100644 files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/fr/web/api/detecting_device_orientation/index.html delete mode 100644 files/fr/web/api/document_object_model/events/index.html delete mode 100644 files/fr/web/guide/events/index.html delete mode 100644 files/fr/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/ja/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/ja/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ja/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/ja/orphaned/web/guide/events/index.html create mode 100644 files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ja/web/api/detecting_device_orientation/index.html delete mode 100644 files/ja/web/api/document_object_model/events/index.html delete mode 100644 files/ja/web/guide/events/event_handlers/index.html delete mode 100644 files/ja/web/guide/events/index.html delete mode 100644 files/ja/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/ja/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/ko/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/ko/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ko/orphaned/web/guide/events/index.html create mode 100644 files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ko/web/api/detecting_device_orientation/index.html delete mode 100644 files/ko/web/api/document_object_model/events/index.html delete mode 100644 files/ko/web/guide/events/index.html delete mode 100644 files/ko/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/pt-br/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/index.html create mode 100644 files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/pt-br/web/api/document_object_model/events/index.html delete mode 100644 files/pt-br/web/guide/events/event_handlers/index.html delete mode 100644 files/pt-br/web/guide/events/index.html delete mode 100644 files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/pt-pt/orphaned/web/guide/events/index.html delete mode 100644 files/pt-pt/web/guide/events/index.html create mode 100644 files/ru/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/ru/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/ru/orphaned/web/guide/events/index.html create mode 100644 files/ru/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/ru/web/api/document_object_model/events/index.html delete mode 100644 files/ru/web/guide/events/event_handlers/index.html delete mode 100644 files/ru/web/guide/events/index.html delete mode 100644 files/ru/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/zh-cn/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-cn/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html create mode 100644 files/zh-cn/orphaned/web/guide/events/overview_of_events_and_handlers/index.html delete mode 100644 files/zh-cn/web/api/detecting_device_orientation/index.html delete mode 100644 files/zh-cn/web/api/document_object_model/events/index.html delete mode 100644 files/zh-cn/web/guide/events/event_handlers/index.html delete mode 100644 files/zh-cn/web/guide/events/index.html delete mode 100644 files/zh-cn/web/guide/events/orientation_and_motion_data_explained/index.html delete mode 100644 files/zh-cn/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/zh-tw/orphaned/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-tw/orphaned/web/api/document_object_model/events/index.html create mode 100644 files/zh-tw/orphaned/web/guide/events/event_handlers/index.html create mode 100644 files/zh-tw/orphaned/web/guide/events/index.html delete mode 100644 files/zh-tw/web/api/detecting_device_orientation/index.html delete mode 100644 files/zh-tw/web/api/document_object_model/events/index.html delete mode 100644 files/zh-tw/web/guide/events/event_handlers/index.html delete mode 100644 files/zh-tw/web/guide/events/index.html diff --git a/files/bn/_redirects.txt b/files/bn/_redirects.txt index 1d401b0273..f9c652b1fd 100644 --- a/files/bn/_redirects.txt +++ b/files/bn/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /bn/docs/DOM /bn/docs/Web/API/Document_Object_Model /bn/docs/HTML/HTML5 /bn/docs/Web/Guide/HTML/HTML5 @@ -30,6 +35,7 @@ /bn/docs/Web/CSS/element /bn/docs/Web/CSS/element() /bn/docs/Web/Guide/API/DOM /bn/docs/conflicting/Web/API/Document_Object_Model /bn/docs/Web/Guide/API/WebRTC /bn/docs/Web/API/WebRTC_API +/bn/docs/Web/Guide/Events /bn/docs/orphaned/Web/Guide/Events /bn/docs/Web/Guide/HTML/Canvas_tutorial /bn/docs/Web/API/Canvas_API/Tutorial /bn/docs/Web/Guide/HTML/Content_Editable /bn/docs/Web/Guide/HTML/Editable_content /bn/docs/Web/Guide/HTML/Forms /bn/docs/Learn/Forms diff --git a/files/bn/_wikihistory.json b/files/bn/_wikihistory.json index 0bdb02ce4d..d48064ffd7 100644 --- a/files/bn/_wikihistory.json +++ b/files/bn/_wikihistory.json @@ -406,12 +406,6 @@ "Sheppy" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:10:51.342Z", - "contributors": [ - "Jeremie" - ] - }, "Web/Guide/Performance": { "modified": "2019-03-23T23:20:59.790Z", "contributors": [ @@ -959,5 +953,11 @@ "contributors": [ "ToufiqAminRumi" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:10:51.342Z", + "contributors": [ + "Jeremie" + ] } } \ No newline at end of file diff --git a/files/bn/orphaned/web/guide/events/index.html b/files/bn/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..2322c7fdf6 --- /dev/null +++ b/files/bn/orphaned/web/guide/events/index.html @@ -0,0 +1,38 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

+ +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+

The network requests made by a web page might trigger some events.

+

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+

Docs

+

{{LandingPageListSubpages}}

diff --git a/files/bn/web/guide/events/index.html b/files/bn/web/guide/events/index.html deleted file mode 100644 index 02a20ce36e..0000000000 --- a/files/bn/web/guide/events/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

-

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

-

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

-

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

-

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

-

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

-

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

-

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

-

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

- -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

-

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

-

The network requests made by a web page might trigger some events.

-

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

-
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
-

Docs

-

{{LandingPageListSubpages}}

diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index ce6c7ba2e9..d52340d3f9 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -652,6 +652,7 @@ /de/docs/Web/Guide/CSS/mehrere_Hintergründe_verwenden /de/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds /de/docs/Web/Guide/DOM /de/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 /de/docs/Web/Guide/DOM/Manipulating_the_browser_history /de/docs/Web/API/History_API +/de/docs/Web/Guide/Events /de/docs/orphaned/Web/Guide/Events /de/docs/Web/Guide/Events/Creating_and_triggering_events /de/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /de/docs/Web/Guide/HTML /de/docs/Learn/HTML /de/docs/Web/Guide/HTML/Canvas_Tutorial /de/docs/Web/API/Canvas_API/Tutorial diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 2f6f7a2997..197cc7d25a 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -6756,13 +6756,6 @@ "M@d Man" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T21:10:49.464Z", - "contributors": [ - "stef4412", - "gportioli" - ] - }, "Web/Guide/Graphics": { "modified": "2019-03-23T23:05:58.536Z", "contributors": [ @@ -14837,5 +14830,12 @@ "contributors": [ "td8" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T21:10:49.464Z", + "contributors": [ + "stef4412", + "gportioli" + ] } } \ No newline at end of file diff --git a/files/de/orphaned/web/guide/events/index.html b/files/de/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..2f50cfec0c --- /dev/null +++ b/files/de/orphaned/web/guide/events/index.html @@ -0,0 +1,54 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

 

+ +

Events bezieht sich sowohl auf ein Entwurfsmuster, das für die asynchrone Behandlung verschiedener Vorfälle, die während der Lebensdauer einer Webseite auftreten, als auch auf die Benennung, Charakterisierung und Verwendung einer großen Anzahl von Vorfällen unterschiedlicher Art.

+ +

Die Übersichtsseite bietet eine Einführung in das Entwurfsmuster und eine Zusammenfassung der Arten von Vorfällen, die von modernen Webbrowsern definiert werden und darauf reagieren.

+ +

Auf der Seite Benutzerdefinierte Ereignisse wird beschrieben, wie das Ereigniscode-Entwurfsmuster in benutzerdefiniertem Code verwendet werden kann, um neue Ereignistypen zu definieren, die von Benutzerobjekten ausgegeben werden, Listener-Funktionen zum Behandeln dieser Ereignisse zu registrieren und die Ereignisse im Benutzercode auszulösen.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/de/web/guide/events/index.html b/files/de/web/guide/events/index.html deleted file mode 100644 index 9fbfac8b89..0000000000 --- a/files/de/web/guide/events/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

 

- -

Events bezieht sich sowohl auf ein Entwurfsmuster, das für die asynchrone Behandlung verschiedener Vorfälle, die während der Lebensdauer einer Webseite auftreten, als auch auf die Benennung, Charakterisierung und Verwendung einer großen Anzahl von Vorfällen unterschiedlicher Art.

- -

Die Übersichtsseite bietet eine Einführung in das Entwurfsmuster und eine Zusammenfassung der Arten von Vorfällen, die von modernen Webbrowsern definiert werden und darauf reagieren.

- -

Auf der Seite Benutzerdefinierte Ereignisse wird beschrieben, wie das Ereigniscode-Entwurfsmuster in benutzerdefiniertem Code verwendet werden kann, um neue Ereignistypen zu definieren, die von Benutzerobjekten ausgegeben werden, Listener-Funktionen zum Behandeln dieser Ereignisse zu registrieren und die Ereignisse im Benutzercode auszulösen.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 4b19728752..073cbf88ad 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1450,7 +1450,7 @@ /es/docs/Referencia_DOM_de_Gecko /es/docs/Web/API/Document_Object_Model /es/docs/Referencia_DOM_de_Gecko/Cómo_espacioenblanco /es/docs/Web/API/Document_Object_Model/Whitespace /es/docs/Referencia_DOM_de_Gecko/Ejemplos /es/docs/Web/API/Document_Object_Model/Examples -/es/docs/Referencia_DOM_de_Gecko/Eventos /es/docs/Web/API/Document_Object_Model/Events +/es/docs/Referencia_DOM_de_Gecko/Eventos /es/docs/orphaned/Web/API/Document_Object_Model/Events /es/docs/Referencia_DOM_de_Gecko/Introducción /es/docs/Web/API/Document_Object_Model/Introduction /es/docs/Referencia_DOM_de_Gecko/Localizando_elementos_DOM_usando_selectores /es/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /es/docs/Referencia_DOM_de_Gecko/Prefacio /es/docs/conflicting/Web/API/Document_Object_Model_9f3a59543838705de7e9b080fde3cc14 @@ -1791,12 +1791,14 @@ /es/docs/Web/API/Coordinates /es/docs/Web/API/GeolocationCoordinates /es/docs/Web/API/Coordinates/latitude /es/docs/Web/API/GeolocationCoordinates/latitude /es/docs/Web/API/DOMString/Cadenas_binarias /es/docs/Web/API/DOMString/Binary +/es/docs/Web/API/Detecting_device_orientation /es/docs/orphaned/Web/API/Detecting_device_orientation /es/docs/Web/API/Document/abrir /es/docs/Web/API/Document/open /es/docs/Web/API/Document/async /es/docs/Web/API/XMLDocument/async /es/docs/Web/API/Document/crearAtributo /es/docs/Web/API/Document/createAttribute /es/docs/Web/API/DocumentOrShadowRoot/getSelection /es/docs/Web/API/Document/getSelection /es/docs/Web/API/DocumentOrShadowRoot/pointerLockElement /es/docs/Web/API/Document/pointerLockElement /es/docs/Web/API/DocumentOrShadowRoot/styleSheets /es/docs/Web/API/Document/styleSheets +/es/docs/Web/API/Document_Object_Model/Events /es/docs/orphaned/Web/API/Document_Object_Model/Events /es/docs/Web/API/Element/accessKey /es/docs/Web/API/HTMLElement/accessKey /es/docs/Web/API/Element/name /es/docs/conflicting/Web/API /es/docs/Web/API/Element/ongotpointercapture /es/docs/Web/API/GlobalEventHandlers/ongotpointercapture @@ -2039,17 +2041,20 @@ /es/docs/Web/Events/wheel /es/docs/Web/API/Element/wheel_event /es/docs/Web/Guide/AJAX/Comunidad /es/docs/Web/Guide/AJAX/Community /es/docs/Web/Guide/AJAX/Primeros_Pasos /es/docs/Web/Guide/AJAX/Getting_Started -/es/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained /es/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/es/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/API/Vibration /es/docs/Web/API/Vibration_API /es/docs/Web/Guide/CSS /es/docs/Learn/CSS /es/docs/Web/Guide/CSS/Cajas_flexibles /es/docs/conflicting/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox /es/docs/Web/Guide/CSS/probando_media_queries /es/docs/Web/CSS/Media_Queries/Testing_media_queries /es/docs/Web/Guide/DOM /es/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 -/es/docs/Web/Guide/DOM/Events /es/docs/Web/Guide/Events +/es/docs/Web/Guide/DOM/Events /es/docs/orphaned/Web/Guide/Events /es/docs/Web/Guide/DOM/Events/Creacion_y_Activación_Eventos /es/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events -/es/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/Events/Orientation_and_motion_data_explained -/es/docs/Web/Guide/DOM/Events/eventos_controlador /es/docs/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +/es/docs/Web/Guide/DOM/Events/eventos_controlador /es/docs/orphaned/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/Events /es/docs/orphaned/Web/Guide/Events /es/docs/Web/Guide/Events/Creating_and_triggering_events /es/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/es/docs/Web/Guide/Events/Event_handlers /es/docs/orphaned/Web/Guide/Events/Event_handlers +/es/docs/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /es/docs/Web/Guide/HTML /es/docs/Learn/HTML /es/docs/Web/Guide/HTML/Canvas_tutorial /es/docs/Web/API/Canvas_API/Tutorial /es/docs/Web/Guide/HTML/Canvas_tutorial/Advanced_animations /es/docs/Web/API/Canvas_API/Tutorial/Advanced_animations diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 4518fc9495..398ac13f69 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -3689,14 +3689,6 @@ "yonatanalexis22" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2020-08-11T08:30:00.189Z", - "contributors": [ - "juancarlos.rmr", - "rayrojas", - "jairopezlo" - ] - }, "Web/API/DeviceMotionEvent": { "modified": "2020-10-15T22:22:26.832Z", "contributors": [ @@ -15147,12 +15139,6 @@ "Nathymig" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:45:13.362Z", - "contributors": [ - "recortes" - ] - }, "Web/API/Document_Object_Model": { "modified": "2019-01-16T16:01:11.054Z", "contributors": [ @@ -16476,13 +16462,6 @@ "Seres" ] }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2019-03-23T23:27:10.499Z", - "contributors": [ - "Sheppy", - "rubencidlara" - ] - }, "Web/API/Vibration_API": { "modified": "2019-03-23T23:03:32.169Z", "contributors": [ @@ -16495,19 +16474,6 @@ "TibicenasDesign" ] }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-01T23:47:25.815Z", - "contributors": [ - "Enesimus", - "alesalva" - ] - }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:27:18.635Z", - "contributors": [ - "Sheppy" - ] - }, "Web/API/Canvas_API/Tutorial/Advanced_animations": { "modified": "2019-03-23T22:11:01.831Z", "contributors": [ @@ -23743,5 +23709,39 @@ "enreda", "Soid" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2020-08-11T08:30:00.189Z", + "contributors": [ + "juancarlos.rmr", + "rayrojas", + "jairopezlo" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:45:13.362Z", + "contributors": [ + "recortes" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-01T23:47:25.815Z", + "contributors": [ + "Enesimus", + "alesalva" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:27:18.635Z", + "contributors": [ + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2019-03-23T23:27:10.499Z", + "contributors": [ + "Sheppy", + "rubencidlara" + ] } } \ No newline at end of file diff --git a/files/es/orphaned/web/api/detecting_device_orientation/index.html b/files/es/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..96afd861e0 --- /dev/null +++ b/files/es/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,279 @@ +--- +title: Detectando la orientación del dispositivo +slug: orphaned/Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

Resumen

+ +

Cada vez más, los dispositivos habilitados para la web son capaces de determinar su orientación; esto hace que estos puedan reportar datos indicando los cambios de su orientación con relación a la fuerza de gravedad. In particular, dispositivos de mano como los teléfonos móviles pueden usar esta información para rotar la pantalla automaticamente para mostrar información en de forma vertical, presentando un vista extendida del contenido de la web cuando el dispositivo de forma que el ancho es mayor que el alto. 

+ +

Hay dos eventos JavaScript que manejan la información de orientación. El primero es {{domxref("DeviceOrientationEvent")}}, que es enviado cuando el aceleromentro detecta un cambio de orientación del dispositivo. Recibiendo y procesando los datos reportados por el evento es posible responder interactivamente a la rotación y aplicar cambios correspondientes al movimiento del dispositivo.

+ +

El segundo evento es {{domxref("DeviceMotionEvent")}}, que es enviado cuando un cambio de la aceleración fue añadido. Esto es diferente de {{domxref("DeviceOrientationEvent")}} por que está escuchando cambios de aceleración mas no de orientación. Los sensores son comunmente capaces de detetar {{domxref("DeviceMotionEvent")}} incluso aquellos sensores de laptops que protegen del movimiento a los disposivitos de almacenamiento. {{domxref("DeviceOrientationEvent")}} es comunmente encontrado en dispositivos móviles.

+ +

Trabajando con eventos de orientación

+ +

Todo lo que necesitas hacer para empezar a recibir cambios de orientación es escuchar el evento {{ event("deviceorientation") }}:

+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

Después de registrar el evento de escucha (en este caso, una función de JavaScript llamada handleOrientation()), tu función de escucha periodicamente será invocada con una actualización de datos.

+ +

La información del evento contiene 4 valores:

+ +
    +
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • +
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • +
+ +

El manejador del evento puede ser similar a lo siguiente:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

Explicación de los Valores de Orientación

+ +

El valor reportado para cada eje indica la cantidad de rotación alrededor de un eje dado, con referencia a un estandar marco de coordenadas. El siguiente enlace describe con mayor detalle la Orientacíon y datos del movimiento explicado que es resumido abajo. 

+ +
    +
  • {{ domxref("DeviceOrientationEvent.alpha") }} representa el movimiento alrededor del eje z, representado en grados con valores que van desde 0 a 360.
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }} representa el movimiento del dispositivo alrededor del eje x, representado en grados con valores que van desde -180 a 180.  Esto representa un movimiento de frente hacia atrás del dispositivo.
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }} representa el movimiento del dispositivo alrededor del eje y, representado en grados con valores que van de -90 a 90. Esto representa un movimiento de izquierda a derecha del dispositivo.
  • +
+ +

Ejemplo de orientación

+ +

Este ejemplo va a funcionar en cualquier nevegador que soporte el evento {{event("deviceorientation")}} y funcione en un dispositivo con capacidades de detectar la orientación.

+ +

Imaginemos una pelota en un jardin:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

Este jardin tiene 200 pixeles de ancho (Si, es uno pequeño), y la pelota esta en el centro:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

Ahora, si nosotros movemos nuestro dispositivo, la pelota va a moverse acorde a este:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positioning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

Aqui el resultado en vivo:

+ +
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
+ +
+

Tener en cuenta: Chrome y Firefox no manejan los angulos de la misma forma, asi que en algunos ejes la dirección se invierte.

+
+ +

Procesando eventos de movimiento

+ +

Eventos de movimiento son manejados de la misma manera que la orientación, con la excepción de que estos tienen sus propios nombres de evento: {{ event("devicemotion") }}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

Lo que realmente ha cambiado es la información proporcionada en {{ domxref("DeviceMotionEvent") }} objeto pasado como parametro de la función HandleMotion.

+ +

El evento de movimiento tiene cuatro propiedades:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

Valores de movimiento explicados

+ +

{{ domxref("DeviceMotionEvent") }} proporciona a los desarrolladores web información sobre la velocidad de los cambios de la posición y orientación del dispositivo. Los cambios son proporcionados por sus tres ejes (ver Datos de orientación y movimiento explicados por más detalles).

+ +

Para {{domxref("DeviceMotionEvent.acceleration","acceleration")}} y {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, los ejes corresponden a lo siguiente:

+ +
    +
  • x: Representa el eje de oeste a este.
  • +
  • y: Representa el eje de sur a norte.
  • +
  • z: Representa el eje perpendicular al suelo.
  • +
+ +

Para {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, la situación es un poco diferente; la información corresponde a lo siguiente en cada caso:

+ +
    +
  • alpha: Representa la velocidad de rotación a lo largo del eje perpendicular a la pantalla ( teclado para desktop).
  • +
  • beta: Representa la velocidad de rotación  a lo largo del eje que va de la izquierda a la derecha del plano de la pantalla (o teclado para desktop).
  • +
  • gamma: Representa la velocidad de rotación  a lo largo del eje que va desde la parte inferior a la parte superrior del plano de la pantalla (o teclado para desktop).
  • +
+ +

Finalmente, {{domxref("DeviceMotionEvent.interval","interval")}} representa el intervalo de tiempo, en milisegundos, en el que los datos han sido obtenidos del dispositivo.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Especificación inicial.
+ +

Compatibilidad con navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
+ 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
+ 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+

Note: gyronorm.js es un polyfill para normalizar los datos del acelerómetro y giroscopio en dispositivos móviles. Esto es útil para superar algunas de las diferencias en la compatibilidad del dispositivo con la orientación del dispositivo..

+
+ +

Gecko implementation notes

+ +
    +
  1. Firefox 3.6, 4, and 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event
  2. +
+ +

Vea también

+ + diff --git a/files/es/orphaned/web/api/document_object_model/events/index.html b/files/es/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..b40c7ce7ae --- /dev/null +++ b/files/es/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,73 @@ +--- +title: Eventos y el DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - DOM + - Guía +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Introducción

+ +

Este capítulo describe el Modelo de Eventos del DOM. Se describe la interfaz Event, así como las interfaces para el registro de eventos en los nodos del DOM, y los oyentes de eventos, y varios ejemplos más largos muestran cómo se relacionan entre sí las diversas interfaces de eventos.

+ +

Hay un diagrama excelente que explica claramente las tres fases del flujo de eventos a través del DOM en el borrador DOM Level 3 Events.

+ +

Vea también el Ejemplo 5: Propagación de eventos en el capítulo de Ejemplos para un ejemplo más detallado de cómo los eventos se mueven a través del DOM.

+ +

Registrando oyentes de eventos

+ +

Hay 3 formas de registrar gestores de eventos para un elemento DOM.

+ +

EventTarget.addEventListener

+ +
// Se supone que myButton es un elemento de botón
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

Este es el método que debe usar en las páginas web modernas. 

+ +

Nota: Internet Explorer 6-8 no admite este método, ofreciendo una API similar {{domxref("EventTarget.attachEvent")}} en su lugar. Para la compatibilidad entre navegadores utilice una de las muchas bibliotecas de JavaScript disponibles.

+ +

Se pueden encontrar más detalles en la página de referencia {{domxref("EventTarget.addEventListener")}}.

+ +

Atributo HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

El código de JavaScript en el atributo pasa el objeto Event por medio del parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

+ +

Debe evitarse esta forma. Hace que el marcado sea más grande y menos legible. El comitido del contenido/estructura y del comportamiento no están bien separadas, por lo que es más difícil encontrar un error.

+ +

Propiedades del elemento DOM

+ +
// Se supone que myButton es un elemento de botón
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

La función se puede defirnir para que tome un parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

+ +

El problema con este método es que solo se puede establecer un gestor por elemento y por evento.

+ +

Accediendo a las Interfaces de eventos

+ +

Los controladores de eventos se pueden adjuntar a varios objetos, incluidos los elementos DOM, documentos, al objeto window, etc. Cuando se produce un evento, se crea un objeto de evento y se pasa secuencialmente a los oyentes del evento.

+ +

Se puede acceder a la interfaz {{domxref ("Evento")}} desde la función del gestor, a través del objeto de evento pasado como primer argumento. El siguiente ejemplo simple muestra cómo se pasa un objeto de evento a la función del controlador de eventos, y se puede usar desde dentro de una de esas funciones.

+ +
function foo(evt) {
+  // al parámetro evt se le asigna automáticamente el objeto event
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/es/orphaned/web/guide/events/event_handlers/index.html b/files/es/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..1c298b7826 --- /dev/null +++ b/files/es/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,133 @@ +--- +title: Manejadores de eventos en el DOM +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

La plataforma Web provee varias formas de recibir notificaciones de los eventos del DOM.  Dos de las formas más comunes son: la general {{domxref("EventTarget.addEventListener", "addEventListener()")}} y un conjunto específico de controladores de eventos específicos. Esta página se enfoca en los detalles de cómo funcionan estos.

+ +

Registering on-event handlers

+ +

Los controladores on-event son un grupo de propiedades ofrecidas por los elementos del DOM para ayudar a manejar cómo los elementos reaccionan a los eventos. Los elementos pueden ser interactivos (por ejemplo: enlaces, botones, imagenes, formularios) or non-interactive (e.g. the base document). Los eventos pueden ser cuando se haga un click, detectar cuando se presione una tecla,  enfocarse, entre otros. Los handlers on-event son comunmente denominados como el evento al cual deben reaccionar, como ser onclick, onkeypress, onfocus, etc.

+ +

Pueden especificar un controlador de evento on<...> para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:

+ +
    +
  • Usando el HTML {{Glossary("atributo")}} llamados on{eventtype} en un elemento, por ejemplo:
    + <button onclick="return handleClick(event);">,
  • +
  • O seteandolo {{Glossary("property/JavaScript", "property")}} desde JavaScript, por ejemplo:
    + document.getElementById("mybutton").onclick = function(event) { ... }.
  • +
+ +

Un controlador onevent

+ +

Notese que cada objeto puede tener sólo un controlador on-event para un evento dado (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

+ +

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like  mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

+ +

Non-element objects

+ +

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

+ +
xhr.onprogress = function() { ... }
+ +

Details

+ +

The value of HTML on<...> attributes and corresponding  JavaScript properties

+ +

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

+ +
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
+
+<script>
+window.onload = function () {
+  var div = document.getElementById("a");
+  console.log("Attribute reflected as a property: ", div.onclick.toString());
+  // Prints: function onclick(event) { alert('old') }
+  div.onclick = function() { alert('new') };
+  console.log("Changed property to: ", div.onclick.toString());
+  // Prints: function () { alert('new') }
+  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
+  // Prints: alert('old')
+}
+</script>
+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event - for all event handlers, except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details see the this keyword documentation.

+ +

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event, for details see "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +

TBD (non-capturing listener)

+ +

Terminology

+ +

The term event handler may be used to refer to:

+ +
    +
  • any function or object registered to be notified of events,
  • +
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • +
+ +

When discussing the various methods of listening to events,

+ +
    +
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • +
  • whereas event handler refers to a function registered via on... attributes or properties.
  • +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ +

Event handler changes in Firefox 9

+ +

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

+ +

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

+ +

Detecting the presence of event handler properties

+ +

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

You can't set or access the values of any IDL-defined attributes on DOM prototype objects; that means you can't, for example, change Window.prototype.onload anymore. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/es/orphaned/web/guide/events/index.html b/files/es/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..f9469eba26 --- /dev/null +++ b/files/es/orphaned/web/guide/events/index.html @@ -0,0 +1,17 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+

Everything you need to know about events will go under here. We're working on cleanup here now.

+

Docs

+

{{LandingPageListSubpages}}

diff --git a/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..d6e7708621 --- /dev/null +++ b/files/es/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,48 @@ +--- +title: Explicación de los datos de orientación y movimiento +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+

Sumario

+

Cuando se utiliza la orientación y los eventos de movimiento, es importante entender cuáles son los significados de los valores en el navegador. En este artículo se proporciona información acerca de los sistemas de coordenadas en el juego y la forma de usarlos.

+
+

Atención: Actualmente, Firefox y Chrome no soporta la orientación de la misma forma. Ten cuidado con esto cuando sea imprementado en un navegador u otro.

+
+

Acerca de los marcos de coordenadas

+

Un marco de coordenadas en un sistema en el que la orientacion de los tres ejers (X, Y y Z) se definen en referencia a un objeto. Hay dos marcos de coordenadas a considerar cuando se utiliza eventos de orientación y el movimiento:

+

Marco de coordenadas terrestres

+

El marco de coordenadas de terrestres es el sistema de coordenadas fijado en el centro de la Tierra, es decir, los ejes están alineados sobre la base de la fuerza de la gravedad y la orientación norte magnético estándar. Utilizamos las letras mayúsculas ("X", "Y" y "Z") para describir los ejes del sistema de coordenadas terrestre.

+
    +
  • El eje X sigue a lo largo (profuncidad) del plano de tierra, perpendicular al eje Y y positiva hacia el este (y por lo tanto negativa hacia el oeste).
  • +
  • El eje Y sigue a lo largo(ancho) del plano de tierra, y es positivo hacia el norte verdadero (es decir, el Polo Norte, el norte no es magnético) y negativo hacia la verdadera sur.
  • +
  • El eje Z es perpendicular al plano de tierra, piensa en él como una línea trazada entre el dispositivo y el centro de la Tierra. El valor de la coordenada Z es positivo hacia arriba (distancia desde el centro de la Tierra) y negativo hacia abajo (hacia el centro de la Tierra).
  • +
+

 

+

+

 

+

Marco de coordenadas del dispositivo

+

El marco de coordenadas del dispositivo es el marco de la coordinación fijada en el centro del dispositivo. Utilizamos letras minúsculas ("x", "y" y "z") para describir los ejes de las coordenadas del del dispositivo

+

axes.png

+
    +
  • El eje x está en el plano de la pantalla y es positiva hacia la derecha y negativa hacia la izquierda.
  • +
  • El eje y está en el plano de la pantalla y es positiva hacia la parte superior y negativa hacia la parte inferior.
  • +
  • El eje z es perpendicular a la pantalla o teclado, y es positivo que se extiende hacia fuera de la pantalla.
  • +
+
+ Nota: En un teléfono o tableta, la orientación del dispositivo siempre se considera en relación con la orientación estándar de la pantalla, lo que es la orientación "retrato" en la mayoría de los dispositivos. En una computadora portátil, la orientación se considera en relación con el teclado. Si desea detectar cambios en la orientación del dispositivo con el fin de compensar, se puede utilizar el evento orientationChange.
+

Sobre la rotación

+

La rotación se describe alrededor de cualquier eje dado en términos del número de grados de diferencia entre el marco de coordenadas del dispositivo y el marco de coordenadas de la Tierra, y se mide en grados.

+

Alpha

+

Rotación alrededor del eje z - es decir, girando el dispositivo - hace que el ángulo de rotación alfa cambie:

+

alpha.png

+

El ángulo alfa es de 0 °, cuando la parte superior del dispositivo se apunta directamente hacia el polo norte de la Tierra, y aumenta a medida que el dispositivo se gira hacia la izquierda.

+

Beta

+

Rotación alrededor del eje X - es decir, inclinando el dispositivo desde o hacia el usuario - hace que el ángulo de giro beta cambie:

+

beta.png

+

El ángulo beta es de 0 ° en la parte superior e inferior del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 180 ° como el dispositivo se inclina hacia adelante y disminuye hacia -180 ° como el dispositivo se inclina hacia atrás.

+

Gamma

+

Rotación alrededor del eje Y - es decir, la inclinación del dispositivo hacia la izquierda o hacia la derecha - hace que el ángulo de giro gamma cambie:

+

gamma.png

+

El ángulo gamma es 0 °, cuando los lados izquierdo y derecho del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 90 ° como el dispositivo se inclina hacia la derecha, y hacia -90 ° como el dispositivo se inclina hacia el izquierda.

diff --git a/files/es/web/api/detecting_device_orientation/index.html b/files/es/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 60302ae643..0000000000 --- a/files/es/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: Detectando la orientación del dispositivo -slug: Web/API/Detecting_device_orientation -translation_of: Web/API/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

Resumen

- -

Cada vez más, los dispositivos habilitados para la web son capaces de determinar su orientación; esto hace que estos puedan reportar datos indicando los cambios de su orientación con relación a la fuerza de gravedad. In particular, dispositivos de mano como los teléfonos móviles pueden usar esta información para rotar la pantalla automaticamente para mostrar información en de forma vertical, presentando un vista extendida del contenido de la web cuando el dispositivo de forma que el ancho es mayor que el alto. 

- -

Hay dos eventos JavaScript que manejan la información de orientación. El primero es {{domxref("DeviceOrientationEvent")}}, que es enviado cuando el aceleromentro detecta un cambio de orientación del dispositivo. Recibiendo y procesando los datos reportados por el evento es posible responder interactivamente a la rotación y aplicar cambios correspondientes al movimiento del dispositivo.

- -

El segundo evento es {{domxref("DeviceMotionEvent")}}, que es enviado cuando un cambio de la aceleración fue añadido. Esto es diferente de {{domxref("DeviceOrientationEvent")}} por que está escuchando cambios de aceleración mas no de orientación. Los sensores son comunmente capaces de detetar {{domxref("DeviceMotionEvent")}} incluso aquellos sensores de laptops que protegen del movimiento a los disposivitos de almacenamiento. {{domxref("DeviceOrientationEvent")}} es comunmente encontrado en dispositivos móviles.

- -

Trabajando con eventos de orientación

- -

Todo lo que necesitas hacer para empezar a recibir cambios de orientación es escuchar el evento {{ event("deviceorientation") }}:

- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

Después de registrar el evento de escucha (en este caso, una función de JavaScript llamada handleOrientation()), tu función de escucha periodicamente será invocada con una actualización de datos.

- -

La información del evento contiene 4 valores:

- -
    -
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • -
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • -
- -

El manejador del evento puede ser similar a lo siguiente:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

Explicación de los Valores de Orientación

- -

El valor reportado para cada eje indica la cantidad de rotación alrededor de un eje dado, con referencia a un estandar marco de coordenadas. El siguiente enlace describe con mayor detalle la Orientacíon y datos del movimiento explicado que es resumido abajo. 

- -
    -
  • {{ domxref("DeviceOrientationEvent.alpha") }} representa el movimiento alrededor del eje z, representado en grados con valores que van desde 0 a 360.
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }} representa el movimiento del dispositivo alrededor del eje x, representado en grados con valores que van desde -180 a 180.  Esto representa un movimiento de frente hacia atrás del dispositivo.
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }} representa el movimiento del dispositivo alrededor del eje y, representado en grados con valores que van de -90 a 90. Esto representa un movimiento de izquierda a derecha del dispositivo.
  • -
- -

Ejemplo de orientación

- -

Este ejemplo va a funcionar en cualquier nevegador que soporte el evento {{event("deviceorientation")}} y funcione en un dispositivo con capacidades de detectar la orientación.

- -

Imaginemos una pelota en un jardin:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

Este jardin tiene 200 pixeles de ancho (Si, es uno pequeño), y la pelota esta en el centro:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

Ahora, si nosotros movemos nuestro dispositivo, la pelota va a moverse acorde a este:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positioning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

Aqui el resultado en vivo:

- -
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
- -
-

Tener en cuenta: Chrome y Firefox no manejan los angulos de la misma forma, asi que en algunos ejes la dirección se invierte.

-
- -

Procesando eventos de movimiento

- -

Eventos de movimiento son manejados de la misma manera que la orientación, con la excepción de que estos tienen sus propios nombres de evento: {{ event("devicemotion") }}

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

Lo que realmente ha cambiado es la información proporcionada en {{ domxref("DeviceMotionEvent") }} objeto pasado como parametro de la función HandleMotion.

- -

El evento de movimiento tiene cuatro propiedades:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

Valores de movimiento explicados

- -

{{ domxref("DeviceMotionEvent") }} proporciona a los desarrolladores web información sobre la velocidad de los cambios de la posición y orientación del dispositivo. Los cambios son proporcionados por sus tres ejes (ver Datos de orientación y movimiento explicados por más detalles).

- -

Para {{domxref("DeviceMotionEvent.acceleration","acceleration")}} y {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, los ejes corresponden a lo siguiente:

- -
    -
  • x: Representa el eje de oeste a este.
  • -
  • y: Representa el eje de sur a norte.
  • -
  • z: Representa el eje perpendicular al suelo.
  • -
- -

Para {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, la situación es un poco diferente; la información corresponde a lo siguiente en cada caso:

- -
    -
  • alpha: Representa la velocidad de rotación a lo largo del eje perpendicular a la pantalla ( teclado para desktop).
  • -
  • beta: Representa la velocidad de rotación  a lo largo del eje que va de la izquierda a la derecha del plano de la pantalla (o teclado para desktop).
  • -
  • gamma: Representa la velocidad de rotación  a lo largo del eje que va desde la parte inferior a la parte superrior del plano de la pantalla (o teclado para desktop).
  • -
- -

Finalmente, {{domxref("DeviceMotionEvent.interval","interval")}} representa el intervalo de tiempo, en milisegundos, en el que los datos han sido obtenidos del dispositivo.

- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Especificación inicial.
- -

Compatibilidad con navegadores

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
- 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
- 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
-

Note: gyronorm.js es un polyfill para normalizar los datos del acelerómetro y giroscopio en dispositivos móviles. Esto es útil para superar algunas de las diferencias en la compatibilidad del dispositivo con la orientación del dispositivo..

-
- -

Gecko implementation notes

- -
    -
  1. Firefox 3.6, 4, and 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event
  2. -
- -

Vea también

- - diff --git a/files/es/web/api/document_object_model/events/index.html b/files/es/web/api/document_object_model/events/index.html deleted file mode 100644 index 5f2c1b47cf..0000000000 --- a/files/es/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Eventos y el DOM -slug: Web/API/Document_Object_Model/Events -tags: - - DOM - - Guía -translation_of: Web/API/Document_Object_Model/Events -original_slug: Referencia_DOM_de_Gecko/Eventos ---- -

Introducción

- -

Este capítulo describe el Modelo de Eventos del DOM. Se describe la interfaz Event, así como las interfaces para el registro de eventos en los nodos del DOM, y los oyentes de eventos, y varios ejemplos más largos muestran cómo se relacionan entre sí las diversas interfaces de eventos.

- -

Hay un diagrama excelente que explica claramente las tres fases del flujo de eventos a través del DOM en el borrador DOM Level 3 Events.

- -

Vea también el Ejemplo 5: Propagación de eventos en el capítulo de Ejemplos para un ejemplo más detallado de cómo los eventos se mueven a través del DOM.

- -

Registrando oyentes de eventos

- -

Hay 3 formas de registrar gestores de eventos para un elemento DOM.

- -

EventTarget.addEventListener

- -
// Se supone que myButton es un elemento de botón
-myButton.addEventListener('click', function(){alert('Hello world');}, false);
-
- -

Este es el método que debe usar en las páginas web modernas. 

- -

Nota: Internet Explorer 6-8 no admite este método, ofreciendo una API similar {{domxref("EventTarget.attachEvent")}} en su lugar. Para la compatibilidad entre navegadores utilice una de las muchas bibliotecas de JavaScript disponibles.

- -

Se pueden encontrar más detalles en la página de referencia {{domxref("EventTarget.addEventListener")}}.

- -

Atributo HTML

- -
<button onclick="alert('Hello world!')">
-
- -

El código de JavaScript en el atributo pasa el objeto Event por medio del parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

- -

Debe evitarse esta forma. Hace que el marcado sea más grande y menos legible. El comitido del contenido/estructura y del comportamiento no están bien separadas, por lo que es más difícil encontrar un error.

- -

Propiedades del elemento DOM

- -
// Se supone que myButton es un elemento de botón
-myButton.onclick = function(event){alert('Hello world');};
-
- -

La función se puede defirnir para que tome un parámetro event. El valor de retorno se trata de una manera especial, descrita en la especificación HTML.

- -

El problema con este método es que solo se puede establecer un gestor por elemento y por evento.

- -

Accediendo a las Interfaces de eventos

- -

Los controladores de eventos se pueden adjuntar a varios objetos, incluidos los elementos DOM, documentos, al objeto window, etc. Cuando se produce un evento, se crea un objeto de evento y se pasa secuencialmente a los oyentes del evento.

- -

Se puede acceder a la interfaz {{domxref ("Evento")}} desde la función del gestor, a través del objeto de evento pasado como primer argumento. El siguiente ejemplo simple muestra cómo se pasa un objeto de evento a la función del controlador de eventos, y se puede usar desde dentro de una de esas funciones.

- -
function foo(evt) {
-  // al parámetro evt se le asigna automáticamente el objeto event
-  alert(evt);
-}
-table_el.onclick = foo;
-
- - - - diff --git a/files/es/web/guide/events/event_handlers/index.html b/files/es/web/guide/events/event_handlers/index.html deleted file mode 100644 index f7bd9ac9e1..0000000000 --- a/files/es/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Manejadores de eventos en el DOM -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers -original_slug: Web/Guide/DOM/Events/eventos_controlador ---- -

La plataforma Web provee varias formas de recibir notificaciones de los eventos del DOM.  Dos de las formas más comunes son: la general {{domxref("EventTarget.addEventListener", "addEventListener()")}} y un conjunto específico de controladores de eventos específicos. Esta página se enfoca en los detalles de cómo funcionan estos.

- -

Registering on-event handlers

- -

Los controladores on-event son un grupo de propiedades ofrecidas por los elementos del DOM para ayudar a manejar cómo los elementos reaccionan a los eventos. Los elementos pueden ser interactivos (por ejemplo: enlaces, botones, imagenes, formularios) or non-interactive (e.g. the base document). Los eventos pueden ser cuando se haga un click, detectar cuando se presione una tecla,  enfocarse, entre otros. Los handlers on-event son comunmente denominados como el evento al cual deben reaccionar, como ser onclick, onkeypress, onfocus, etc.

- -

Pueden especificar un controlador de evento on<...> para un evento en particular (como {{event("click")}}) como un opbjeto determinado de diferentes formas:

- -
    -
  • Usando el HTML {{Glossary("atributo")}} llamados on{eventtype} en un elemento, por ejemplo:
    - <button onclick="return handleClick(event);">,
  • -
  • O seteandolo {{Glossary("property/JavaScript", "property")}} desde JavaScript, por ejemplo:
    - document.getElementById("mybutton").onclick = function(event) { ... }.
  • -
- -

Un controlador onevent

- -

Notese que cada objeto puede tener sólo un controlador on-event para un evento dado (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

- -

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like  mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

- -

Non-element objects

- -

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

- -
xhr.onprogress = function() { ... }
- -

Details

- -

The value of HTML on<...> attributes and corresponding  JavaScript properties

- -

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

- -
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
-
-<script>
-window.onload = function () {
-  var div = document.getElementById("a");
-  console.log("Attribute reflected as a property: ", div.onclick.toString());
-  // Prints: function onclick(event) { alert('old') }
-  div.onclick = function() { alert('new') };
-  console.log("Changed property to: ", div.onclick.toString());
-  // Prints: function () { alert('new') }
-  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
-  // Prints: alert('old')
-}
-</script>
- -

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

- -

Event handler's parameters, this binding, and the return value

- -

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

- -
    -
  • event - for all event handlers, except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as string.
  • -
- -

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details see the this keyword documentation.

- -

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event, for details see "The event handler processing algorithm" in the HTML specification.

- -

When the event handler is invoked

- -

TBD (non-capturing listener)

- -

Terminology

- -

The term event handler may be used to refer to:

- -
    -
  • any function or object registered to be notified of events,
  • -
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • -
- -

When discussing the various methods of listening to events,

- -
    -
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • -
  • whereas event handler refers to a function registered via on... attributes or properties.
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

Browser compatibility

- -

Event handler changes in Firefox 9

- -

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

- -

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

- -

Detecting the presence of event handler properties

- -

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

You can't set or access the values of any IDL-defined attributes on DOM prototype objects; that means you can't, for example, change Window.prototype.onload anymore. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/es/web/guide/events/index.html b/files/es/web/guide/events/index.html deleted file mode 100644 index a9e55742fa..0000000000 --- a/files/es/web/guide/events/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - TopicStub - - events -translation_of: Web/Guide/Events -original_slug: Web/Guide/DOM/Events ---- -

{{draft()}}

-

Everything you need to know about events will go under here. We're working on cleanup here now.

-

Docs

-

{{LandingPageListSubpages}}

diff --git a/files/es/web/guide/events/orientation_and_motion_data_explained/index.html b/files/es/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index 8c700f6a71..0000000000 --- a/files/es/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Explicación de los datos de orientación y movimiento -slug: Web/Guide/Events/Orientation_and_motion_data_explained -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained -original_slug: >- - Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained/Orientation_and_motion_data_explained ---- -

{{ Draft() }}

-

Sumario

-

Cuando se utiliza la orientación y los eventos de movimiento, es importante entender cuáles son los significados de los valores en el navegador. En este artículo se proporciona información acerca de los sistemas de coordenadas en el juego y la forma de usarlos.

-
-

Atención: Actualmente, Firefox y Chrome no soporta la orientación de la misma forma. Ten cuidado con esto cuando sea imprementado en un navegador u otro.

-
-

Acerca de los marcos de coordenadas

-

Un marco de coordenadas en un sistema en el que la orientacion de los tres ejers (X, Y y Z) se definen en referencia a un objeto. Hay dos marcos de coordenadas a considerar cuando se utiliza eventos de orientación y el movimiento:

-

Marco de coordenadas terrestres

-

El marco de coordenadas de terrestres es el sistema de coordenadas fijado en el centro de la Tierra, es decir, los ejes están alineados sobre la base de la fuerza de la gravedad y la orientación norte magnético estándar. Utilizamos las letras mayúsculas ("X", "Y" y "Z") para describir los ejes del sistema de coordenadas terrestre.

-
    -
  • El eje X sigue a lo largo (profuncidad) del plano de tierra, perpendicular al eje Y y positiva hacia el este (y por lo tanto negativa hacia el oeste).
  • -
  • El eje Y sigue a lo largo(ancho) del plano de tierra, y es positivo hacia el norte verdadero (es decir, el Polo Norte, el norte no es magnético) y negativo hacia la verdadera sur.
  • -
  • El eje Z es perpendicular al plano de tierra, piensa en él como una línea trazada entre el dispositivo y el centro de la Tierra. El valor de la coordenada Z es positivo hacia arriba (distancia desde el centro de la Tierra) y negativo hacia abajo (hacia el centro de la Tierra).
  • -
-

 

-

-

 

-

Marco de coordenadas del dispositivo

-

El marco de coordenadas del dispositivo es el marco de la coordinación fijada en el centro del dispositivo. Utilizamos letras minúsculas ("x", "y" y "z") para describir los ejes de las coordenadas del del dispositivo

-

axes.png

-
    -
  • El eje x está en el plano de la pantalla y es positiva hacia la derecha y negativa hacia la izquierda.
  • -
  • El eje y está en el plano de la pantalla y es positiva hacia la parte superior y negativa hacia la parte inferior.
  • -
  • El eje z es perpendicular a la pantalla o teclado, y es positivo que se extiende hacia fuera de la pantalla.
  • -
-
- Nota: En un teléfono o tableta, la orientación del dispositivo siempre se considera en relación con la orientación estándar de la pantalla, lo que es la orientación "retrato" en la mayoría de los dispositivos. En una computadora portátil, la orientación se considera en relación con el teclado. Si desea detectar cambios en la orientación del dispositivo con el fin de compensar, se puede utilizar el evento orientationChange.
-

Sobre la rotación

-

La rotación se describe alrededor de cualquier eje dado en términos del número de grados de diferencia entre el marco de coordenadas del dispositivo y el marco de coordenadas de la Tierra, y se mide en grados.

-

Alpha

-

Rotación alrededor del eje z - es decir, girando el dispositivo - hace que el ángulo de rotación alfa cambie:

-

alpha.png

-

El ángulo alfa es de 0 °, cuando la parte superior del dispositivo se apunta directamente hacia el polo norte de la Tierra, y aumenta a medida que el dispositivo se gira hacia la izquierda.

-

Beta

-

Rotación alrededor del eje X - es decir, inclinando el dispositivo desde o hacia el usuario - hace que el ángulo de giro beta cambie:

-

beta.png

-

El ángulo beta es de 0 ° en la parte superior e inferior del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 180 ° como el dispositivo se inclina hacia adelante y disminuye hacia -180 ° como el dispositivo se inclina hacia atrás.

-

Gamma

-

Rotación alrededor del eje Y - es decir, la inclinación del dispositivo hacia la izquierda o hacia la derecha - hace que el ángulo de giro gamma cambie:

-

gamma.png

-

El ángulo gamma es 0 °, cuando los lados izquierdo y derecho del dispositivo son la misma distancia de la superficie de la Tierra, y aumenta hacia 90 ° como el dispositivo se inclina hacia la derecha, y hacia -90 ° como el dispositivo se inclina hacia el izquierda.

diff --git a/files/fi/_redirects.txt b/files/fi/_redirects.txt index c2937a661e..f2e8d44654 100644 --- a/files/fi/_redirects.txt +++ b/files/fi/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /fi/docs/DOM /fi/docs/Web/API/Document_Object_Model /fi/docs/DOM/navigator.doNotTrack /fi/docs/Web/API/Navigator/doNotTrack @@ -28,6 +33,7 @@ /fi/docs/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/orphaned/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/Skinin_luominen_Firefoxiin:Aloittaminen /fi/docs/orphaned/Skinin_luominen_Firefoxiin/Aloittaminen /fi/docs/Teemat /fi/docs/orphaned/Teemat +/fi/docs/Web/Guide/Events /fi/docs/orphaned/Web/Guide/Events /fi/docs/WebGL /fi/docs/Web/API/WebGL_API /fi/docs/demos /fi/docs/orphaned/demos /fi/docs/demos/detail /fi/docs/orphaned/demos/detail diff --git a/files/fi/_wikihistory.json b/files/fi/_wikihistory.json index e27e7c560b..46b1d2e151 100644 --- a/files/fi/_wikihistory.json +++ b/files/fi/_wikihistory.json @@ -95,12 +95,6 @@ "chrisdavidmills" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T21:37:53.387Z", - "contributors": [ - "gportioli" - ] - }, "Web/HTML": { "modified": "2019-09-10T15:19:38.441Z", "contributors": [ @@ -356,5 +350,11 @@ "contributors": [ "Prasanth" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T21:37:53.387Z", + "contributors": [ + "gportioli" + ] } } \ No newline at end of file diff --git a/files/fi/orphaned/web/guide/events/index.html b/files/fi/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..43aec7dec1 --- /dev/null +++ b/files/fi/orphaned/web/guide/events/index.html @@ -0,0 +1,54 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+ +

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+ +

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/fi/web/guide/events/index.html b/files/fi/web/guide/events/index.html deleted file mode 100644 index 0196a78f5a..0000000000 --- a/files/fi/web/guide/events/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index b6cf255d2a..430ba7ed9e 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -3625,6 +3625,7 @@ /fr/docs/Web/API/Console/erreur /fr/docs/Web/API/Console/error /fr/docs/Web/API/Coordinates /fr/docs/Web/API/GeolocationCoordinates /fr/docs/Web/API/DOMTokenList/DOMTokenList.add() /fr/docs/Web/API/DOMTokenList/add +/fr/docs/Web/API/Detecting_device_orientation /fr/docs/orphaned/Web/API/Detecting_device_orientation /fr/docs/Web/API/DeviceOrientationEvent.absolute /fr/docs/Web/API/DeviceOrientationEvent/absolute /fr/docs/Web/API/DeviceRotationRate /fr/docs/Web/API/DeviceMotionEventRotationRate /fr/docs/Web/API/DeviceRotationRate/alpha /fr/docs/Web/API/DeviceMotionEventRotationRate/alpha @@ -3661,9 +3662,10 @@ /fr/docs/Web/API/DocumentOrShadowRoot/elementsFromPoint /fr/docs/Web/API/Document/elementsFromPoint /fr/docs/Web/API/DocumentOrShadowRoot/getSelection /fr/docs/Web/API/Document/getSelection /fr/docs/Web/API/DocumentOrShadowRoot/styleSheets /fr/docs/Web/API/Document/styleSheets +/fr/docs/Web/API/Document_Object_Model/Events /fr/docs/orphaned/Web/API/Document_Object_Model/Events /fr/docs/Web/API/Document_Object_Model/Exemples /fr/docs/Web/API/Document_Object_Model/Examples /fr/docs/Web/API/Document_Object_Model/Introduction_au_DOM /fr/docs/Web/API/Document_Object_Model/Introduction -/fr/docs/Web/API/Document_Object_Model/Les_évènements_et_le_DOM /fr/docs/Web/API/Document_Object_Model/Events +/fr/docs/Web/API/Document_Object_Model/Les_évènements_et_le_DOM /fr/docs/orphaned/Web/API/Document_Object_Model/Events /fr/docs/Web/API/Document_Object_Model/Localisation_des_éléments_DOM_avec_les_sélecteurs /fr/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /fr/docs/Web/API/Document_Object_Model/Préface /fr/docs/conflicting/Web/API/Document_Object_Model_03f6e13c52ad7c539d9b4c33c51ac4a3 /fr/docs/Web/API/Document_Object_Model/document /fr/docs/Web/API/Document @@ -4417,9 +4419,9 @@ /fr/docs/Web/Guide/CSS /fr/docs/Learn/CSS /fr/docs/Web/Guide/CSS/Flexible_boxes /fr/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox /fr/docs/Web/Guide/DOM /fr/docs/conflicting/Web/API/Document_Object_Model_656f0e51418b39c498011268be9b3a10 -/fr/docs/Web/Guide/DOM/Events /fr/docs/Web/Guide/Events +/fr/docs/Web/Guide/DOM/Events /fr/docs/orphaned/Web/Guide/Events /fr/docs/Web/Guide/DOM/Events/Creating_and_triggering_events /fr/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events -/fr/docs/Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées /fr/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/fr/docs/Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées /fr/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/Web/Guide/DOM/Events/Touch_events /fr/docs/Web/API/Touch_events /fr/docs/Web/Guide/DOM/Events/Touch_events/Gérer_à_la_fois_événement_tactile_et_événement_de_la_souris /fr/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent /fr/docs/Web/Guide/DOM/Manipuler l'historique du navigateur /fr/docs/Web/API/History_API @@ -4427,7 +4429,9 @@ /fr/docs/Web/Guide/DOM/Manipuler_historique_du_navigateur /fr/docs/Web/API/History_API /fr/docs/Web/Guide/DOM/Manipuler_historique_du_navigateur/Example /fr/docs/Web/API/History_API/Example /fr/docs/Web/Guide/DOM/Using_full_screen_mode /fr/docs/Web/API/Fullscreen_API +/fr/docs/Web/Guide/Events /fr/docs/orphaned/Web/Guide/Events /fr/docs/Web/Guide/Events/Creating_and_triggering_events /fr/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/fr/docs/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /fr/docs/Web/Guide/Graphics/Dessiner_avec_canvas /fr/docs/conflicting/Web/API/Canvas_API/Tutorial /fr/docs/Web/Guide/HTML /fr/docs/Learn/HTML /fr/docs/Web/Guide/HTML/Astuces_de_création_de_pages_HTML_à_affichage_rapide /fr/docs/Learn/HTML/Howto/Author_fast-loading_HTML_pages @@ -5704,7 +5708,7 @@ /fr/docs/Web/XSLT/Éléments/element /fr/docs/Web/XSLT/Element/element /fr/docs/WebAPI /fr/docs/conflicting/Web/API_dd04ca1265cb79b990b8120e5f5070d3 /fr/docs/WebAPI/Battery_Status /fr/docs/Web/API/Battery_status_API -/fr/docs/WebAPI/Detecting_device_orientation /fr/docs/Web/API/Detecting_device_orientation +/fr/docs/WebAPI/Detecting_device_orientation /fr/docs/orphaned/Web/API/Detecting_device_orientation /fr/docs/WebAPI/Network_Information /fr/docs/Web/API/Network_Information_API /fr/docs/WebAPI/Pointer_Lock /fr/docs/Web/API/Pointer_Lock_API /fr/docs/WebAPI/Proximity /fr/docs/Web/API/Proximity_Events diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index 271068eb88..59a24a90c4 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -33255,12 +33255,6 @@ "Fredchat" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:39:20.100Z", - "contributors": [ - "loella16" - ] - }, "Web/API/Document_object_model/Locating_DOM_elements_using_selectors": { "modified": "2019-03-18T21:39:30.176Z", "contributors": [ @@ -35215,19 +35209,6 @@ "wordsbybird" ] }, - "Web/Guide/Events": { - "modified": "2020-08-30T07:20:46.985Z", - "contributors": [ - "Voulto", - "Sheppy" - ] - }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2019-03-18T21:41:00.371Z", - "contributors": [ - "loella16" - ] - }, "Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent": { "modified": "2019-03-18T21:33:21.001Z", "contributors": [ @@ -43462,18 +43443,6 @@ "Fredchat" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2019-03-23T23:28:22.437Z", - "contributors": [ - "mgagnon555", - "a-mt", - "tregagnon", - "Fredchat", - "FredB", - "achraf", - "darnuria" - ] - }, "Web/API/Network_Information_API": { "modified": "2020-10-15T21:24:14.258Z", "contributors": [ @@ -45335,5 +45304,36 @@ "yasakura_", "jmh" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2019-03-23T23:28:22.437Z", + "contributors": [ + "mgagnon555", + "a-mt", + "tregagnon", + "Fredchat", + "FredB", + "achraf", + "darnuria" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:39:20.100Z", + "contributors": [ + "loella16" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2020-08-30T07:20:46.985Z", + "contributors": [ + "Voulto", + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2019-03-18T21:41:00.371Z", + "contributors": [ + "loella16" + ] } } \ No newline at end of file diff --git a/files/fr/orphaned/web/api/detecting_device_orientation/index.html b/files/fr/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..42b8cec296 --- /dev/null +++ b/files/fr/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,220 @@ +--- +title: Détecter l'orientation de l'appareil +slug: orphaned/Web/API/Detecting_device_orientation +tags: + - Device Orientation + - Firefox OS + - Mobile + - Motion + - Orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +

{{SeeCompatTable}}

+ +

Résumé

+ +

De plus en plus d'appareils connectés à Internet sont capable de déterminer leur orientation. C'est-à-dire qu'ils peuvent fournir des données indiquant des changements dans leur orientation par rapport à la gravité. En particulier les appareils portables, comme les téléphones mobiles, peuvent utiliser cette information pour effectuer automatiquement une rotation de l'écran, afin de toujours proposer la meilleure disposition possible pour le contenu à afficher.

+ +

Il existe deux événements JavaScript pour gérer l'orientation. Le premier est {{domxref("DeviceOrientationEvent")}}, qui est envoyé quand l'accéléromètre détecte un changement d'orientation de l'appareil. En recevant et en analysant les données fournies par ces événements d'orientation, il est possible de répondre de manière interactive aux changements d'orientation et d'élévation causés par les mouvements imprimés à l'appareil par l'utilisateur.

+ +

Le second événement est {{ domxref("DeviceMotionEvent") }}, qui est envoyé quand un changement d’accélération est ajouté. Il est différent de {{domxref("DeviceOrientationEvent")}}, car il écoute les changements d'accélération par opposition à l'orientation. Parmi les capteurs capables de détecter {{ domxref("DeviceMotionEvent") }}, on trouve les capteurs des ordinateurs portables utilisés pour protéger des chutes les périphériques de stockage. Ils sont communément présents dans les appareils mobiles (tablettes, téléphones intelligents).

+ +

Traitement des événements d'orientation

+ +

Tout ce dont vous avez besoin pour commencer à recevoir les changements d'orientation est d’écouter l’événement {{ event("deviceorientation") }} :

+ +
+

Note: gyronorm.js est un polyfill pour normaliser les données de l'accéléromètre et du gyroscope sur les appareils mobiles. C'est utile pour surmonter certaines différences dans la prise en charge des périphériques pour l'orientation du périphérique.

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

Après l’enregistrement de votre gestionnaire d'événements (event listener en anglais), dans ce cas, une fonction JS appelée handleOrientation(), votre fonction d'écoute est appelée périodiquement pour récupérer les données de l'orientation mise à jour.

+ +

L'événement d'orientation contient quatre valeurs ::

+ +
    +
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • +
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • +
  • {{domxref("DeviceOrientationEvent.beta")}}
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • +
+ +

La fonction gérant l’événement pourrait ressembler à ceci :

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Faites quelque chose avec les données acquises. ;)
+}
+
+ +

Détail des valeurs d'orientation

+ +

La valeur reportée pour chaque axe indique l'angle de rotation autour d'un axe donné, en référence à un système de coordonnées standard. Ces valeurs sont décrites de façon plus détaillée dans cet article Orientation et déplacement expliquée.

+ +
    +
  • La valeur {{ domxref("DeviceOrientationEvent.alpha") }} représente le mouvement de l'appareil, autour de l'axe « z », en degrés sur une échelle de 0° à 360° ;
  • +
  • La valeur {{ domxref("DeviceOrientationEvent.beta") }} représente le mouvement de l'appareil autour de l'axe « y » en degrés, sur une échelle de -180° à 180°.  Cela représente le mouvement d'avant en arrière de l'appareil ;
  • +
  • La valeur {{ domxref("DeviceOrientationEvent.gamma") }} représente le mouvement de l'appareil autour de l'axe « x », exprimée en degrés sur une échelle de -90° à 90°. Cela représente le mouvement de gauche à droite de l'appareil.
  • +
+ +

Exemple d'orientation

+ +

Cet exemple fonctionne sur tout navigateur supportant l’événement {{event("deviceorientation")}} et sur tout appareil capable de détecter son orientation.

+ +

Imaginons une balle dans un jardin :

+ +
<div class="jardin">
+  <div class="balle"></div>
+</div>
+
+<pre class="resultat"></pre>
+
+ +

Ce jardin fait 200 pixels de long (Oui c'est un « petit » jardin !), et la balle est au centre :

+ +
.jardin {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.balle {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

Maintenant, on définit le déplacement de la balle en fonction de celui de l'appareil :

+ +
var jardin = document.querySelector('.jardin'),
+    balle = document.querySelector('.balle'),
+    resultat = document.querySelector('.resultat'),
+    maxX = jardin.clientWidth  - balle.clientWidth,
+    maxY = jardin.clientHeight - balle.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta,  // En degré sur l'interval [-180,180].
+      y = event.gamma; // En degré sur l'interval [-90,90].
+
+  resultat.innerHTML  = "beta : " + x + "<br />";
+  resultat.innerHTML += "gamma: " + y + "<br />";
+
+  // Parce-que l'on ne veut pas avoir l'appareil à l'envers.
+  // On restreint les valeurs de x à l'intervalle [-90,90].
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+  // Pour rendre le calcul plus simple.
+  // On délimite l'intervalle de x et y sur [0, 180].
+  x += 90;
+  y += 90;
+
+  // 10 est la moitié de la taille de la balle.
+  // Cela centre le point de positionnement au centre de la balle.
+
+  balle.style.top  = (maxX * x / 180 - 10) + "px";
+  balle.style.left = (maxY * y / 180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

Et voici le résultat en temps réel :

+ +
{{EmbedLiveSample("Exemple_d'orientation", '230', '260')}}
+ +
 
+ +
{{LiveSampleLink("Exemple_d'orientation", "Cliquez ici")}} pour ouvrir cet exemple dans une nouvelle fenêtre;  l'événement {{event("deviceorientation")}} ne marche pas dans les {{HTMLElement("iframe", "iframes")}} cross-origin dans tous les navigateurs.
+ +
 
+ +
+

Attention : Chrome et Firefox ne gèrent pas les angles de la même façon, certaines directions sur les axes sont inversées.

+
+ +

Traiter les événement de mouvement

+ +

Les événements de mouvement gèrent l'orientation de la même façon à l'exception près qu’ils portent un nom d’événement différent : {{event("devicemotion")}}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+
+ +

Ce qui change réellement est l'information fournie par l'objet {{ domxref("DeviceMotionEvent") }} passée comme paramètre par la fonction HandleMotion.

+ +

Les événements de mouvement contiennent quatre propriétés :

+ +
    +
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • +
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • +
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • +
  • {{domxref("DeviceMotionEvent.interval")}}
  • +
+ +

Explication des valeurs de mouvement

+ +

L'objet {{ domxref("DeviceMotionEvent") }} fourni aux développeurs Web des informations sur la vitesse de changement d'orientation et de position de l'appareil. Les changements rapportés sont fournis pour les trois axes (voir Orientation et déplacement expliquées pour les détails).

+ +

Pour {{domxref("DeviceMotionEvent.acceleration","acceleration")}} et {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, Les axes correspondent à :

+ +
    +
  • x : représente l'axe d'Ouest en Est ;
  • +
  • y : représente l'axe Sud vers Nord :
  • +
  • z : représente l'axe perpendiculaire au sol.
  • +
+ +

Pour {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, c'est un peu différent. L'information correspond à :

+ +
    +
  • alpha : représente le ratio de rotation le long de l'axe perpendiculaire à l'écran (ou du clavier au bureau) ;
  • +
  • bêta : représente le ratio de rotation le long de l'axe allant de la gauche vers la droite de l'écran (ou du clavier au bureau) ;
  • +
  • gamma : représente le ratio de rotation le long de l'axe allant du bas vers le haut de l'écran (ou clavier vers le bureau).
  • +
+ +

Au final, {{domxref("DeviceMotionEvent.interval","interval")}} représente l'intervalle de temps, en millisecondes, pour les données générées par l'appareil.

+ +

Spécifications

+ + + + + + + + + + + + + + + + +
SpécificationStatutCommentaires
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Spécification initiale.
+ +

Compatibilité des navigateurs

+ +

{{Compat("api.DeviceOrientationEvent")}}

+ +

Voir aussi

+ + diff --git a/files/fr/orphaned/web/api/document_object_model/events/index.html b/files/fr/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..7e3d544c5a --- /dev/null +++ b/files/fr/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,75 @@ +--- +title: Les évènements et le DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - API + - DOM + - Guide + - évènements +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Introduction

+ +

Ce chapitre décrit le modèle d'événement DOM. L'interface Event elle-même est décrite, ainsi que les interfaces pour l'enregistrement des évènements sur les noeuds dans le DOM, les écouteurs d'évènements et d'autres exemples montrant les relations des différentes interfaces d'évènements entre elles.

+ +

Il existe un excellent diagramme qui explique clairement les trois phases du flux d'évènements à travers le DOM dans le document sur les évènements DOM Niveau 3.

+ +

Voir aussi l'exemple 5 : Propagation des évènements dans le chapitre "Exemples" pour des exemples détaillés sur le déplacement des évènements à travers le DOM.

+ +

Enregistrement des écouteurs d'évènements

+ +

Il y a 3 moyens d'enregistrer les gestionnaires d'évènements pour un élément DOM.

+ +

EventTarget.addEventListener

+ +
// Supposons que myButton est un élément de bouton
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

C'est la méthode à utiliser dans les pages web modernes.

+ +

Note : Internet Explorer 6-8 ne prend pas en charge cette méthode, il offre une API similaire {{domxref("EventTarget.attachEvent")}} à la place. Pour la compatibilité entre navigateurs, utilisez l'une des nombreuses bibliothèques JavaScript disponibles.

+ +

Plus de détails peuvent être trouvés sur la page de référence {{domxref("EventTarget.addEventListener")}}.

+ +

attribut HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

Le code JavaScript de l'attribut est passé à l'objet évènement par le paramètre event. La valeur renvoyée est traitée d'une façon spéciale décrite dans la spécification HTML.

+ +

Ce moyen devrait être évité. Cela rend le balisage plus grand et moins lisible. Les aspects de contenu / structure et comportement ne sont pas bien séparés, rendant un bogue plus difficile à trouver.

+ +

Propriétés d'un élément DOM

+ +
// Supposons que myButton est un élément de bouton
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

La fonction peut être définie pour prendre un paramètre d'event. La valeur renvoyée est traitée de façon spéciale décrite dans la spécification HTML.

+ +

Le problème avec cette méthode est qu'un seul gestionnaire peut être défini par élément et par évènement.

+ +

Accès aux interfaces d'évènements

+ +

Les gestionnaires d'évènements peuvent être attachés à divers objets y compris les éléments DOM, le document, l'objet fenêtre, etc. Lorsqu'un évènement se produit, un objet évènement est créé et passé séquentiellement aux écouteurs d'évènements.

+ +

L'interface {{domxref("Event")}} est accessible à partir de la fonction gestionnaire, via l'objet événement passé en premier argument. L'exemple simple suivant montre comment un objet d'événement est transmis à la fonction de gestionnaire d'événements et peut être utilisé à partir d'une telle fonction.

+ +
function foo(evt) {
+  // le paramètre evt est automatiquement assigné à l'objet évènement
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/fr/orphaned/web/guide/events/index.html b/files/fr/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..4ed6e68693 --- /dev/null +++ b/files/fr/orphaned/web/guide/events/index.html @@ -0,0 +1,19 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Tout ce que vous devez savoir sur les événements sera présenté ici. Nous travaillons sur le nettoyage ici maintenant.

+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..e0d044bfb2 --- /dev/null +++ b/files/fr/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,77 @@ +--- +title: Les données d'orientation et de mouvement expliquées +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +tags: + - Coordonnées + - Mobile + - Mouvement + - Orientation + - rotation +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+ +

Résumé

+ +

Lorsque vous utilisez des événements d'orientation et de mouvement, il est important de comprendre les valeurs que vous donne le navigateur. Cet article fournit des détails sur les systèmes de coordonnées en jeu et comment vous les utilisez.

+ +
+

Attention : Actuellement, Firefox et Chrome ne gèrent pas ces  coordonnées de la même manière. Prenez-y garde en les utilisant.

+
+ +

À propos des cadres de coordonnées

+ +

Un cadre de coordonnées est un système grâce auquel l'orientation des trois axes (X, Y et Z) d'un objet est définie. Il existe deux cadres de coordonnées à prendre en compte lors de l'utilisation d'événements d'orientation et de mouvement:

+ +

Le cadre de coordonnées de la Terre

+ +

Le cadre de coordonnées de la Terre est celui basé sur le centre de la Terre ; c'est-à-dire que les axes sont alignés sur la base de l'attraction de la gravité et de l'orientation nord magnétique standard. Nous utilisons des lettres majuscules ("X", "Y" et "Z") pour décrire les axes du cadre de coordonnées de la Terre.

+ +
    +
  • L'axe X  suit le plan du sol, perpendiculaire à l'axe Y, et positif vers l'est (et donc négatif vers l'ouest).
  • +
  • L'axe Y suit le plan du sol et est positif vers le vrai nord (c'est-à-dire le pôle nord, pas le nord magnétique) et négatif vers le vrai sud.
  • +
  • L'axe Z est perpendiculaire au plan du sol ; pensez-y comme une ligne tracée entre l'appareil et le centre de la Terre. La valeur de la coordonnée Z est positive vers le haut (loin du centre de la Terre) et négative vers le bas (vers le centre de la Terre).
  • +
+ +

Le cadre de coordonnées de l'appareil

+ +

Le cadre de coordonnées de l'appareil est basé sur le centre de l'appareil. Nous utilisons des lettres minuscules ("x", "y" et "z") pour décrire les axes du cadre de coordonnées de l'appareil.

+ +

axes.png

+ +
    +
  • L'axe x est dans le plan de l'écran et est positif vers la droite et négatif vers la gauche.
  • +
  • L'axe y est dans le plan de l'écran et est positif vers le haut et négatif vers le bas.
  • +
  • L'axe z est perpendiculaire à l'écran ou au clavier et positif à partir de l'écran.
  • +
+ +
Note : Sur un téléphone ou une tablette, l'orientation de l'appareil est toujours considérée par rapport à l'orientation standard de l'écran ; c'est l'orientation "portrait" sur la plupart des appareils. Sur un ordinateur portable, l'orientation est considérée par rapport au clavier. Si vous voulez détecter les changements d'orientation de l'appareil pour compenser, vous pouvez utiliser l'évènement orientationchange.
+ +

À propos de la rotation

+ +

La rotation est décrite  pour un axe donné en nombre de degrés d'écart entre le cadre de coordonnées de l'appareil et le cadre de coordonnées de la Terre, et est mesurée en degrés.

+ +

Alpha

+ +

La rotation autour de l'axe z -- c'est-à-dire, son déplacement latéral, vers la gauche ou la droite - fait changer l'angle de rotation alpha :

+ +

alpha.png

+ +

L'angle alpha est de 0° quand le haut de l'appareil pointe vers le pôle nord, et augmente lorsque l'appareil est tourné vers la gauche.

+ +

Beta

+ +

La rotation autour de l'axe x -- c'est-à-dire, l'inclinaison de l'appareil de ou vers l'utilisateur -- provoque le changement de l'angle de rotation beta :

+ +

beta.png

+ +

L'angle beta est de 0° lorsque le haut et le bas de l'appareil sont à la même distance de la surface de la Terre, et augmente vers 180 ° lorsque l'appareil est incliné vers l'avant et diminue vers -180 ° lorsque l'appareil est incliné vers l'arrière.

+ +

Gamma

+ +

La rotation autour de l'axe Y -- c'est-à-dire, l'inclinaison de l'appareil vers la gauche ou la droite -- modifie l'angle de rotation gamma :

+ +

gamma.png

+ +

L'angle gamma est de 0° lorsque les côtés gauche et droit de l'appareil sont à la même distance de la surface de la Terre et augmente vers 90 ° lorsque l'appareil est incliné vers la droite, et vers -90 ° lorsque l'appareil est incliné vers la gauche.

diff --git a/files/fr/web/api/detecting_device_orientation/index.html b/files/fr/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 32d45270a1..0000000000 --- a/files/fr/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Détecter l'orientation de l'appareil -slug: Web/API/Detecting_device_orientation -tags: - - Device Orientation - - Firefox OS - - Mobile - - Motion - - Orientation -translation_of: Web/API/Detecting_device_orientation -original_slug: WebAPI/Detecting_device_orientation ---- -

{{SeeCompatTable}}

- -

Résumé

- -

De plus en plus d'appareils connectés à Internet sont capable de déterminer leur orientation. C'est-à-dire qu'ils peuvent fournir des données indiquant des changements dans leur orientation par rapport à la gravité. En particulier les appareils portables, comme les téléphones mobiles, peuvent utiliser cette information pour effectuer automatiquement une rotation de l'écran, afin de toujours proposer la meilleure disposition possible pour le contenu à afficher.

- -

Il existe deux événements JavaScript pour gérer l'orientation. Le premier est {{domxref("DeviceOrientationEvent")}}, qui est envoyé quand l'accéléromètre détecte un changement d'orientation de l'appareil. En recevant et en analysant les données fournies par ces événements d'orientation, il est possible de répondre de manière interactive aux changements d'orientation et d'élévation causés par les mouvements imprimés à l'appareil par l'utilisateur.

- -

Le second événement est {{ domxref("DeviceMotionEvent") }}, qui est envoyé quand un changement d’accélération est ajouté. Il est différent de {{domxref("DeviceOrientationEvent")}}, car il écoute les changements d'accélération par opposition à l'orientation. Parmi les capteurs capables de détecter {{ domxref("DeviceMotionEvent") }}, on trouve les capteurs des ordinateurs portables utilisés pour protéger des chutes les périphériques de stockage. Ils sont communément présents dans les appareils mobiles (tablettes, téléphones intelligents).

- -

Traitement des événements d'orientation

- -

Tout ce dont vous avez besoin pour commencer à recevoir les changements d'orientation est d’écouter l’événement {{ event("deviceorientation") }} :

- -
-

Note: gyronorm.js est un polyfill pour normaliser les données de l'accéléromètre et du gyroscope sur les appareils mobiles. C'est utile pour surmonter certaines différences dans la prise en charge des périphériques pour l'orientation du périphérique.

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

Après l’enregistrement de votre gestionnaire d'événements (event listener en anglais), dans ce cas, une fonction JS appelée handleOrientation(), votre fonction d'écoute est appelée périodiquement pour récupérer les données de l'orientation mise à jour.

- -

L'événement d'orientation contient quatre valeurs ::

- -
    -
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • -
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • -
  • {{domxref("DeviceOrientationEvent.beta")}}
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • -
- -

La fonction gérant l’événement pourrait ressembler à ceci :

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Faites quelque chose avec les données acquises. ;)
-}
-
- -

Détail des valeurs d'orientation

- -

La valeur reportée pour chaque axe indique l'angle de rotation autour d'un axe donné, en référence à un système de coordonnées standard. Ces valeurs sont décrites de façon plus détaillée dans cet article Orientation et déplacement expliquée.

- -
    -
  • La valeur {{ domxref("DeviceOrientationEvent.alpha") }} représente le mouvement de l'appareil, autour de l'axe « z », en degrés sur une échelle de 0° à 360° ;
  • -
  • La valeur {{ domxref("DeviceOrientationEvent.beta") }} représente le mouvement de l'appareil autour de l'axe « y » en degrés, sur une échelle de -180° à 180°.  Cela représente le mouvement d'avant en arrière de l'appareil ;
  • -
  • La valeur {{ domxref("DeviceOrientationEvent.gamma") }} représente le mouvement de l'appareil autour de l'axe « x », exprimée en degrés sur une échelle de -90° à 90°. Cela représente le mouvement de gauche à droite de l'appareil.
  • -
- -

Exemple d'orientation

- -

Cet exemple fonctionne sur tout navigateur supportant l’événement {{event("deviceorientation")}} et sur tout appareil capable de détecter son orientation.

- -

Imaginons une balle dans un jardin :

- -
<div class="jardin">
-  <div class="balle"></div>
-</div>
-
-<pre class="resultat"></pre>
-
- -

Ce jardin fait 200 pixels de long (Oui c'est un « petit » jardin !), et la balle est au centre :

- -
.jardin {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.balle {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

Maintenant, on définit le déplacement de la balle en fonction de celui de l'appareil :

- -
var jardin = document.querySelector('.jardin'),
-    balle = document.querySelector('.balle'),
-    resultat = document.querySelector('.resultat'),
-    maxX = jardin.clientWidth  - balle.clientWidth,
-    maxY = jardin.clientHeight - balle.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta,  // En degré sur l'interval [-180,180].
-      y = event.gamma; // En degré sur l'interval [-90,90].
-
-  resultat.innerHTML  = "beta : " + x + "<br />";
-  resultat.innerHTML += "gamma: " + y + "<br />";
-
-  // Parce-que l'on ne veut pas avoir l'appareil à l'envers.
-  // On restreint les valeurs de x à l'intervalle [-90,90].
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-  // Pour rendre le calcul plus simple.
-  // On délimite l'intervalle de x et y sur [0, 180].
-  x += 90;
-  y += 90;
-
-  // 10 est la moitié de la taille de la balle.
-  // Cela centre le point de positionnement au centre de la balle.
-
-  balle.style.top  = (maxX * x / 180 - 10) + "px";
-  balle.style.left = (maxY * y / 180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

Et voici le résultat en temps réel :

- -
{{EmbedLiveSample("Exemple_d'orientation", '230', '260')}}
- -
 
- -
{{LiveSampleLink("Exemple_d'orientation", "Cliquez ici")}} pour ouvrir cet exemple dans une nouvelle fenêtre;  l'événement {{event("deviceorientation")}} ne marche pas dans les {{HTMLElement("iframe", "iframes")}} cross-origin dans tous les navigateurs.
- -
 
- -
-

Attention : Chrome et Firefox ne gèrent pas les angles de la même façon, certaines directions sur les axes sont inversées.

-
- -

Traiter les événement de mouvement

- -

Les événements de mouvement gèrent l'orientation de la même façon à l'exception près qu’ils portent un nom d’événement différent : {{event("devicemotion")}}

- -
window.addEventListener("devicemotion", handleMotion, true);
-
- -

Ce qui change réellement est l'information fournie par l'objet {{ domxref("DeviceMotionEvent") }} passée comme paramètre par la fonction HandleMotion.

- -

Les événements de mouvement contiennent quatre propriétés :

- -
    -
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • -
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • -
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • -
  • {{domxref("DeviceMotionEvent.interval")}}
  • -
- -

Explication des valeurs de mouvement

- -

L'objet {{ domxref("DeviceMotionEvent") }} fourni aux développeurs Web des informations sur la vitesse de changement d'orientation et de position de l'appareil. Les changements rapportés sont fournis pour les trois axes (voir Orientation et déplacement expliquées pour les détails).

- -

Pour {{domxref("DeviceMotionEvent.acceleration","acceleration")}} et {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}, Les axes correspondent à :

- -
    -
  • x : représente l'axe d'Ouest en Est ;
  • -
  • y : représente l'axe Sud vers Nord :
  • -
  • z : représente l'axe perpendiculaire au sol.
  • -
- -

Pour {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}, c'est un peu différent. L'information correspond à :

- -
    -
  • alpha : représente le ratio de rotation le long de l'axe perpendiculaire à l'écran (ou du clavier au bureau) ;
  • -
  • bêta : représente le ratio de rotation le long de l'axe allant de la gauche vers la droite de l'écran (ou du clavier au bureau) ;
  • -
  • gamma : représente le ratio de rotation le long de l'axe allant du bas vers le haut de l'écran (ou clavier vers le bureau).
  • -
- -

Au final, {{domxref("DeviceMotionEvent.interval","interval")}} représente l'intervalle de temps, en millisecondes, pour les données générées par l'appareil.

- -

Spécifications

- - - - - - - - - - - - - - - - -
SpécificationStatutCommentaires
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Spécification initiale.
- -

Compatibilité des navigateurs

- -

{{Compat("api.DeviceOrientationEvent")}}

- -

Voir aussi

- - diff --git a/files/fr/web/api/document_object_model/events/index.html b/files/fr/web/api/document_object_model/events/index.html deleted file mode 100644 index 053a61a2dc..0000000000 --- a/files/fr/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Les évènements et le DOM -slug: Web/API/Document_Object_Model/Events -tags: - - API - - DOM - - Guide - - évènements -translation_of: Web/API/Document_Object_Model/Events -original_slug: Web/API/Document_Object_Model/Les_évènements_et_le_DOM ---- -

Introduction

- -

Ce chapitre décrit le modèle d'événement DOM. L'interface Event elle-même est décrite, ainsi que les interfaces pour l'enregistrement des évènements sur les noeuds dans le DOM, les écouteurs d'évènements et d'autres exemples montrant les relations des différentes interfaces d'évènements entre elles.

- -

Il existe un excellent diagramme qui explique clairement les trois phases du flux d'évènements à travers le DOM dans le document sur les évènements DOM Niveau 3.

- -

Voir aussi l'exemple 5 : Propagation des évènements dans le chapitre "Exemples" pour des exemples détaillés sur le déplacement des évènements à travers le DOM.

- -

Enregistrement des écouteurs d'évènements

- -

Il y a 3 moyens d'enregistrer les gestionnaires d'évènements pour un élément DOM.

- -

EventTarget.addEventListener

- -
// Supposons que myButton est un élément de bouton
-myButton.addEventListener('click', function(){alert('Hello world');}, false);
-
- -

C'est la méthode à utiliser dans les pages web modernes.

- -

Note : Internet Explorer 6-8 ne prend pas en charge cette méthode, il offre une API similaire {{domxref("EventTarget.attachEvent")}} à la place. Pour la compatibilité entre navigateurs, utilisez l'une des nombreuses bibliothèques JavaScript disponibles.

- -

Plus de détails peuvent être trouvés sur la page de référence {{domxref("EventTarget.addEventListener")}}.

- -

attribut HTML

- -
<button onclick="alert('Hello world!')">
-
- -

Le code JavaScript de l'attribut est passé à l'objet évènement par le paramètre event. La valeur renvoyée est traitée d'une façon spéciale décrite dans la spécification HTML.

- -

Ce moyen devrait être évité. Cela rend le balisage plus grand et moins lisible. Les aspects de contenu / structure et comportement ne sont pas bien séparés, rendant un bogue plus difficile à trouver.

- -

Propriétés d'un élément DOM

- -
// Supposons que myButton est un élément de bouton
-myButton.onclick = function(event){alert('Hello world');};
-
- -

La fonction peut être définie pour prendre un paramètre d'event. La valeur renvoyée est traitée de façon spéciale décrite dans la spécification HTML.

- -

Le problème avec cette méthode est qu'un seul gestionnaire peut être défini par élément et par évènement.

- -

Accès aux interfaces d'évènements

- -

Les gestionnaires d'évènements peuvent être attachés à divers objets y compris les éléments DOM, le document, l'objet fenêtre, etc. Lorsqu'un évènement se produit, un objet évènement est créé et passé séquentiellement aux écouteurs d'évènements.

- -

L'interface {{domxref("Event")}} est accessible à partir de la fonction gestionnaire, via l'objet événement passé en premier argument. L'exemple simple suivant montre comment un objet d'événement est transmis à la fonction de gestionnaire d'événements et peut être utilisé à partir d'une telle fonction.

- -
function foo(evt) {
-  // le paramètre evt est automatiquement assigné à l'objet évènement
-  alert(evt);
-}
-table_el.onclick = foo;
-
- - - - diff --git a/files/fr/web/guide/events/index.html b/files/fr/web/guide/events/index.html deleted file mode 100644 index 79b85e1372..0000000000 --- a/files/fr/web/guide/events/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - TopicStub - - events -translation_of: Web/Guide/Events -original_slug: Web/Guide/DOM/Events ---- -

{{draft()}}

- -

Tout ce que vous devez savoir sur les événements sera présenté ici. Nous travaillons sur le nettoyage ici maintenant.

- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html b/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index d6b0145e3e..0000000000 --- a/files/fr/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Les données d'orientation et de mouvement expliquées -slug: Web/Guide/Events/Orientation_and_motion_data_explained -tags: - - Coordonnées - - Mobile - - Mouvement - - Orientation - - rotation -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained -original_slug: Web/Guide/DOM/Events/Les_données_d_orientation_et_de_mouvement_expliquées ---- -

{{ Draft() }}

- -

Résumé

- -

Lorsque vous utilisez des événements d'orientation et de mouvement, il est important de comprendre les valeurs que vous donne le navigateur. Cet article fournit des détails sur les systèmes de coordonnées en jeu et comment vous les utilisez.

- -
-

Attention : Actuellement, Firefox et Chrome ne gèrent pas ces  coordonnées de la même manière. Prenez-y garde en les utilisant.

-
- -

À propos des cadres de coordonnées

- -

Un cadre de coordonnées est un système grâce auquel l'orientation des trois axes (X, Y et Z) d'un objet est définie. Il existe deux cadres de coordonnées à prendre en compte lors de l'utilisation d'événements d'orientation et de mouvement:

- -

Le cadre de coordonnées de la Terre

- -

Le cadre de coordonnées de la Terre est celui basé sur le centre de la Terre ; c'est-à-dire que les axes sont alignés sur la base de l'attraction de la gravité et de l'orientation nord magnétique standard. Nous utilisons des lettres majuscules ("X", "Y" et "Z") pour décrire les axes du cadre de coordonnées de la Terre.

- -
    -
  • L'axe X  suit le plan du sol, perpendiculaire à l'axe Y, et positif vers l'est (et donc négatif vers l'ouest).
  • -
  • L'axe Y suit le plan du sol et est positif vers le vrai nord (c'est-à-dire le pôle nord, pas le nord magnétique) et négatif vers le vrai sud.
  • -
  • L'axe Z est perpendiculaire au plan du sol ; pensez-y comme une ligne tracée entre l'appareil et le centre de la Terre. La valeur de la coordonnée Z est positive vers le haut (loin du centre de la Terre) et négative vers le bas (vers le centre de la Terre).
  • -
- -

Le cadre de coordonnées de l'appareil

- -

Le cadre de coordonnées de l'appareil est basé sur le centre de l'appareil. Nous utilisons des lettres minuscules ("x", "y" et "z") pour décrire les axes du cadre de coordonnées de l'appareil.

- -

axes.png

- -
    -
  • L'axe x est dans le plan de l'écran et est positif vers la droite et négatif vers la gauche.
  • -
  • L'axe y est dans le plan de l'écran et est positif vers le haut et négatif vers le bas.
  • -
  • L'axe z est perpendiculaire à l'écran ou au clavier et positif à partir de l'écran.
  • -
- -
Note : Sur un téléphone ou une tablette, l'orientation de l'appareil est toujours considérée par rapport à l'orientation standard de l'écran ; c'est l'orientation "portrait" sur la plupart des appareils. Sur un ordinateur portable, l'orientation est considérée par rapport au clavier. Si vous voulez détecter les changements d'orientation de l'appareil pour compenser, vous pouvez utiliser l'évènement orientationchange.
- -

À propos de la rotation

- -

La rotation est décrite  pour un axe donné en nombre de degrés d'écart entre le cadre de coordonnées de l'appareil et le cadre de coordonnées de la Terre, et est mesurée en degrés.

- -

Alpha

- -

La rotation autour de l'axe z -- c'est-à-dire, son déplacement latéral, vers la gauche ou la droite - fait changer l'angle de rotation alpha :

- -

alpha.png

- -

L'angle alpha est de 0° quand le haut de l'appareil pointe vers le pôle nord, et augmente lorsque l'appareil est tourné vers la gauche.

- -

Beta

- -

La rotation autour de l'axe x -- c'est-à-dire, l'inclinaison de l'appareil de ou vers l'utilisateur -- provoque le changement de l'angle de rotation beta :

- -

beta.png

- -

L'angle beta est de 0° lorsque le haut et le bas de l'appareil sont à la même distance de la surface de la Terre, et augmente vers 180 ° lorsque l'appareil est incliné vers l'avant et diminue vers -180 ° lorsque l'appareil est incliné vers l'arrière.

- -

Gamma

- -

La rotation autour de l'axe Y -- c'est-à-dire, l'inclinaison de l'appareil vers la gauche ou la droite -- modifie l'angle de rotation gamma :

- -

gamma.png

- -

L'angle gamma est de 0° lorsque les côtés gauche et droit de l'appareil sont à la même distance de la surface de la Terre et augmente vers 90 ° lorsque l'appareil est incliné vers la droite, et vers -90 ° lorsque l'appareil est incliné vers la gauche.

diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 093e37fee3..7c9273da6e 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -1280,7 +1280,7 @@ /ja/docs/DOM/DOMString /ja/docs/Web/API/DOMString /ja/docs/DOM/DOMTimeStamp /ja/docs/Web/API/DOMTimeStamp /ja/docs/DOM/DOM_Reference /ja/docs/Web/API/Document_Object_Model -/ja/docs/DOM/DOM_Reference/Events /ja/docs/Web/API/Document_Object_Model/Events +/ja/docs/DOM/DOM_Reference/Events /ja/docs/orphaned/Web/API/Document_Object_Model/Events /ja/docs/DOM/DOM_Reference/Examples /ja/docs/Web/API/Document_Object_Model/Examples /ja/docs/DOM/DOM_Reference/Introduction /ja/docs/Web/API/Document_Object_Model/Introduction /ja/docs/DOM/DOM_Reference/Preface /ja/docs/conflicting/Web/API/Document_Object_Model_8435a25d5137b436d5d7161e1b813c02 @@ -1385,7 +1385,7 @@ /ja/docs/DOM/NodeIterator /ja/docs/Web/API/NodeIterator /ja/docs/DOM/NodeList /ja/docs/Web/API/NodeList /ja/docs/DOM/NodeList.item /ja/docs/Web/API/NodeList/item -/ja/docs/DOM/Orientation_and_motion_data_explained /ja/docs/Web/Guide/Events/Orientation_and_motion_data_explained +/ja/docs/DOM/Orientation_and_motion_data_explained /ja/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained /ja/docs/DOM/Plugin /ja/docs/Web/API/Plugin /ja/docs/DOM/PluginArray /ja/docs/Web/API/PluginArray /ja/docs/DOM/SVGFontElement /ja/docs/Web/API/SVGFontElement @@ -1993,7 +1993,7 @@ /ja/docs/DebNews /ja/docs/orphaned/DebNews /ja/docs/DebNews/20081118 /ja/docs/orphaned/DevNews/20081118 /ja/docs/Deer_Park /ja/docs/Mozilla/Firefox/Releases/1.5 -/ja/docs/Detecting_device_orientation /ja/docs/Web/API/Detecting_device_orientation +/ja/docs/Detecting_device_orientation /ja/docs/orphaned/Web/API/Detecting_device_orientation /ja/docs/Determining_the_dimensions_of_elements /ja/docs/conflicting/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements /ja/docs/DevNews /ja/docs/orphaned/DevNews /ja/docs/DevNews/20060705 /ja/docs/orphaned/DevNews/20060705 @@ -3742,6 +3742,7 @@ /ja/docs/Web/API/Coordinates /ja/docs/Web/API/GeolocationCoordinates /ja/docs/Web/API/DOMCursor.done /ja/docs/Web/API/DOMCursor/done /ja/docs/Web/API/DOMRequest.error /ja/docs/Web/API/DOMRequest/error +/ja/docs/Web/API/Detecting_device_orientation /ja/docs/orphaned/Web/API/Detecting_device_orientation /ja/docs/Web/API/DeviceAcceleration /ja/docs/Web/API/DeviceMotionEventAcceleration /ja/docs/Web/API/DeviceLightEvent.value /ja/docs/Web/API/DeviceLightEvent/value /ja/docs/Web/API/Document.domConfig /ja/docs/Web/API/Document @@ -3763,6 +3764,7 @@ /ja/docs/Web/API/DocumentOrShadowRoot/nodesFromPoint /ja/docs/conflicting/Web/API/DocumentOrShadowRoot_20ea0e1d91453a020aad3a16dbce16f1 /ja/docs/Web/API/DocumentOrShadowRoot/pointerLockElement /ja/docs/Web/API/Document/pointerLockElement /ja/docs/Web/API/DocumentOrShadowRoot/styleSheets /ja/docs/Web/API/Document/styleSheets +/ja/docs/Web/API/Document_Object_Model/Events /ja/docs/orphaned/Web/API/Document_Object_Model/Events /ja/docs/Web/API/Document_Object_Model/Preface /ja/docs/conflicting/Web/API/Document_Object_Model_8435a25d5137b436d5d7161e1b813c02 /ja/docs/Web/API/Element.contentEditable /ja/docs/Web/API/HTMLElement/contentEditable /ja/docs/Web/API/Element.isContentEditable /ja/docs/Web/API/HTMLElement/isContentEditable @@ -3773,7 +3775,7 @@ /ja/docs/Web/API/Element/name /ja/docs/conflicting/Web/API /ja/docs/Web/API/Event/button /ja/docs/conflicting/Web/API/MouseEvent/button /ja/docs/Web/API/Event/createEvent /ja/docs/conflicting/Web/API/Document/createEvent -/ja/docs/Web/API/EventHandler /ja/docs/Web/Guide/Events/Event_handlers +/ja/docs/Web/API/EventHandler /ja/docs/orphaned/Web/Guide/Events/Event_handlers /ja/docs/Web/API/EventTarget.addEventListener /ja/docs/Web/API/EventTarget/addEventListener /ja/docs/Web/API/EventTarget.dispatchEvent /ja/docs/Web/API/EventTarget/dispatchEvent /ja/docs/Web/API/EventTarget.removeEventListener /ja/docs/Web/API/EventTarget/removeEventListener @@ -4573,7 +4575,11 @@ /ja/docs/Web/Guide/DOM/Manipulating_the_browser_history/Working_with_the_History_API /ja/docs/Web/API/History_API/Working_with_the_History_API /ja/docs/Web/Guide/DOM/Using_full_screen_mode /ja/docs/Web/API/Fullscreen_API /ja/docs/Web/Guide/DOM/Whitespace_in_the_DOM /ja/docs/Web/API/Document_Object_Model/Whitespace +/ja/docs/Web/Guide/Events /ja/docs/orphaned/Web/Guide/Events /ja/docs/Web/Guide/Events/Creating_and_triggering_events /ja/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ja/docs/Web/Guide/Events/Event_handlers /ja/docs/orphaned/Web/Guide/Events/Event_handlers +/ja/docs/Web/Guide/Events/Orientation_and_motion_data_explained /ja/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +/ja/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ja/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ja/docs/Web/Guide/Graphics/Drawing_graphics_with_canvas /ja/docs/conflicting/Web/API/Canvas_API/Tutorial_3cd5468edc15a1ef1ddc0d2b17e1fa5d /ja/docs/Web/Guide/HTML /ja/docs/Learn/HTML /ja/docs/Web/Guide/HTML/Canvas_tutorial /ja/docs/conflicting/Web/API/Canvas_API/Tutorial diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index c8a29de950..0a54926ffe 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -11424,15 +11424,6 @@ "chikoski" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2020-10-15T21:21:30.973Z", - "contributors": [ - "YujiSoftware", - "hamasaki", - "yyss", - "Fajrovulpo" - ] - }, "Web/API/DeviceLightEvent": { "modified": "2020-10-15T21:33:03.860Z", "contributors": [ @@ -12749,15 +12740,6 @@ "Okome" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-09-27T12:30:54.835Z", - "contributors": [ - "mfuji09", - "dskmori", - "keeponbeat", - "mikamikuh" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-06-14T18:12:08.377Z", "contributors": [ @@ -32695,35 +32677,6 @@ "ethertank" ] }, - "Web/Guide/Events": { - "modified": "2019-03-18T20:59:28.336Z", - "contributors": [ - "mfuji09", - "gportioli" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-30T04:00:41.655Z", - "contributors": [ - "mfuji09", - "k-kuwahara", - "silverskyvicto", - "momdo" - ] - }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2020-07-25T12:40:06.161Z", - "contributors": [ - "mfuji09", - "yyss" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-03-18T21:46:16.505Z", - "contributors": [ - "superyusuke" - ] - }, "Web/Guide/Graphics": { "modified": "2019-10-11T10:49:15.066Z", "contributors": [ @@ -53496,5 +53449,52 @@ "y4m4to", "lv7777" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2020-10-15T21:21:30.973Z", + "contributors": [ + "YujiSoftware", + "hamasaki", + "yyss", + "Fajrovulpo" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-09-27T12:30:54.835Z", + "contributors": [ + "mfuji09", + "dskmori", + "keeponbeat", + "mikamikuh" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-30T04:00:41.655Z", + "contributors": [ + "mfuji09", + "k-kuwahara", + "silverskyvicto", + "momdo" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-18T20:59:28.336Z", + "contributors": [ + "mfuji09", + "gportioli" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2020-07-25T12:40:06.161Z", + "contributors": [ + "mfuji09", + "yyss" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-03-18T21:46:16.505Z", + "contributors": [ + "superyusuke" + ] } } \ No newline at end of file diff --git a/files/ja/orphaned/web/api/detecting_device_orientation/index.html b/files/ja/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..484067e66f --- /dev/null +++ b/files/ja/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,229 @@ +--- +title: デバイスの方向の検出 +slug: orphaned/Web/API/Detecting_device_orientation +tags: + - API + - Device Orientation + - Firefox OS + - Intermediate + - Mobile + - Motion + - Orientation + - Reference + - WebAPI +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

Web を利用可能なデバイスは、自身の方向を特定できるようになってきました。つまりデバイスは、重力との関係による自身の向きの変化を示すデータを報告できます。特に携帯電話のようなハンドヘルドデバイスは、表示内容が直立し続けるよう自動的に回転させるためにこの情報を使用でき、画面の幅が高さより大きくなるようにデバイスを回転させたときは、Web コンテンツをワイドスクリーン表示にします。

+ +

方向の情報を制御する JavaScript イベントが 2 つあります。ひとつは {{domxref("DeviceOrientationEvent")}} であり、加速度センサーがデバイスの方向の変化を検出したときに発生します。Orientation イベントが報告するデータを受け取って処理することで、ユーザがデバイスを動かすことによる方向や高さの変化に対してインタラクティブに応答できるようになります。

+ +

もうひとつのイベントは {{domxref("DeviceMotionEvent")}} であり、加速度が変化したときに発生します。こちらは方向ではなく加速度の変化を監視することが、{{domxref("DeviceOrientationEvent")}} との違いです。一般的に {{domxref("DeviceMotionEvent")}} を検出できるセンサーには、可動部があるストレージ装置を保護するためラップトップパソコンに内蔵するものも含みます。{{domxref("DeviceOrientationEvent")}} は、モバイルデバイスでとても一般的です。

+ +

orientation イベントを処理する

+ +

方向の変化を受け取り始めるには、{{event("deviceorientation")}} イベントをリッスンします:

+ +
+

注記: gyronorm.js は、モバイルデバイスの加速度センサーやジャイロスコープのデータを正規化するためのポリフィルです。これは、デバイスの方向のサポート状況の違いを克服するのに役立ちます。

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

イベントリスナ (この例では handleOrientation() という名前の JavaScript 関数) を登録すると、リスナ関数は最新の方向データとともに、周期的に呼び出されます。

+ +

Orientation イベントは 4 つの値を持ちます:

+ +
    +
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • +
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • +
  • {{domxref("DeviceOrientationEvent.beta")}}
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • +
+ +

イベントハンドラ関数は以下のようなものです:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // 新たな方向データに基づいて処理を行う
+}
+
+ +

方向として示される値

+ +

それぞれの軸で報告される値は、標準座標系の軸を中心にした回転量を表します。これらは方向および動きとして示されるデータの記事で詳しく説明しており、ここでは概要を記載します。

+ +
    +
  • {{domxref("DeviceOrientationEvent.alpha")}} の値は z 軸を中心にしたデバイスの動きを表し、0 から 360 の範囲による度数で表されます。
  • +
  • {{domxref("DeviceOrientationEvent.beta")}} の値は x 軸を中心にしたデバイスの動きを表し、-180 から 180 の範囲の値による度数で表されます。これはデバイスの前後の動きです。
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}} の値は y 軸を中心にしたデバイスの動きを表し、-90 から 90 の範囲の値による度数で表されます。これはデバイスの左右の動きです。
  • +
+ +

+ +

このサンプルは方向を検出可能なデバイス上で、{{event("deviceorientation")}} イベントをサポートするブラウザを実行する場合に動作します。

+ +

庭にボールがあると考えます:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

庭の幅は 200 ピクセルであり (小さな庭です)、ボールは中心にあります:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

デバイスを動かすと、その動きに応じてボールが移動します:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // -180 から 180 の範囲で角度を示す
+  var y = event.gamma; // -90 から 90 の範囲で角度を示す
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // デバイスをひっくり返したくはないため、
+  // x の値を -90 から 90 の範囲に制限する
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // 計算を容易にするため、x および y の値の範囲を
+  // 0 から 180 に変換する
+  x += 90;
+  y += 90;
+
+  // 10 は、ボールのサイズの半分である。
+  // これにより、配置場所をボールの中心に合わせる
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

結果を以下に示します:

+ +
{{EmbedLiveSample('Orientation_example', '230', '260')}}
+ +
+

警告: Chrome と Firefox では角度の扱い方が異なり、一部の軸の向きが逆になっています。

+
+ +

motion イベントを処理する

+ +

motion イベントは orientation イベントと同じ方法で扱えますが、イベント名は {{event("devicemotion")}} になります。

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

実際どのように変化したかの情報は、HandleMotion 関数のパラメータとして渡す {{domxref("DeviceMotionEvent")}} オブジェクトが提供します。

+ +

motion イベントは 4 つのプロパティを持ちます:

+ +
    +
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • +
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • +
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • +
  • {{domxref("DeviceMotionEvent.interval")}}
  • +
+ +

動きとして示される値

+ +

{{domxref("DeviceMotionEvent")}} オブジェクトは Web 開発者に、デバイスの位置や方向が変化した速度の情報を提供します。変化量は 3 つの軸 (詳しくは方向および動きとして示されるデータをご覧ください) に沿って表します。

+ +

{{domxref("DeviceMotionEvent.acceleration","acceleration")}} および {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}} で対応する軸は以下のとおりです:

+ +
    +
  • x: 西から東へ向かう軸を表します。
  • +
  • y: 南から北へ向かう軸を表します。
  • +
  • z: 地面から直立する軸を表します。
  • +
+ +

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}} では状況が若干異なります。こちらの情報はそれぞれ以下のように対応します:

+ +
    +
  • alpha: スクリーン (デスクトップ環境ではキーボード) から直立する軸を表します。
  • +
  • beta: スクリーンの面 (デスクトップ環境ではキーボード) の左から右へ向かう軸に沿った回転量を表します。
  • +
  • gamma: スクリーンの面 (デスクトップ環境ではキーボード) の下から上へ向かう軸に沿った回転量を表します。
  • +
+ +

最後に {{domxref("DeviceMotionEvent.interval","interval")}} は、デバイスからデータを取得する間隔をミリ秒単位で表します。

+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}最初の仕様
+ +

ブラウザ実装状況

+ +
+

DeviceMotionEvent

+ + + +

{{Compat("api.DeviceMotionEvent")}}

+ +

DeviceOrientationEvent

+ + + +

{{Compat("api.DeviceOrientationEvent")}}

+
+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/api/document_object_model/events/index.html b/files/ja/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..7443168f11 --- /dev/null +++ b/files/ja/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,89 @@ +--- +title: イベントと DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - DOM + - Guide + - ガイド +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +
{{DefaultAPISidebar("DOM")}}
+ +

はじめに

+ +

この章では DOM のイベントモデルを説明します。この Event インターフェイス自身は、 DOM のノード上にイベントを登録する為のインターフェイスと同様であり、イベントリスナーであるとも言えます。いくつかの長い例は、様々な Event インターフェイスがどのように他と関連するかを示します。

+ +

DOM レベル 3 イベントの原案に、DOM を通して 3 つのフェーズから構成されるイベントフローを明確に説明した素晴らしい説明図があります。

+ +

また、イベントが DOM 内をどのように伝播するかについては更に詳細なコード例、例 5: イベント伝播 (propagation) を参照してください。

+ +

イベントリスナーの登録

+ +

DOM の要素にイベントハンドラーを登録する方法は 3 つあります。

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// myButton は button 要素だと仮定します
+myButton.addEventListener('click', greet, false);
+function greet(event){
+    // print and have a look at the event object
+    // always print arguments in case of overlooking any other arguments
+    console.log('greet:', arguments)
+    alert('hello world')
+}
+
+ +

これが最近のウェブページで使われる方法です。

+ +
+

注: Internet Explorer 6 から 8 はこの方法をサポートせず、 {{domxref("EventTarget.attachEvent")}} という似た API を代わりにサポートします。ブラウザー間の互換性を確保するには、数多くある JavaScript ライブラリのうちの一つを使用してください。

+
+ +

さらに詳細を知りたい場合は {{domxref("EventTarget.addEventListener")}} のリファレンスを参照してください。

+ +

HTML 属性

+ +
<button onclick="alert('Hello world!')">
+
+ +

HTML 属性に書かれたこの JavaScript コードには、 event 引数を通してイベントオブジェクトが渡されます。返値は HTML の仕様で定義された特別な方法で処理されます

+ +
+

警告: この方法は避けてください。これはマークアップを増加させ、可読性を下げます。コンテンツと振る舞いが正しく分離されておらず、バグの発見が困難になります。

+
+ +

DOM 要素のプロパティ

+ +
// myButton は button 要素と仮定します
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

この関数は 1 つの event 引数を取るように定義できます。返り値は HTML の仕様で定義された特別な方法で処理されます

+ +

この書き方の問題は、各要素の各イベント毎に 1 つだけしかハンドラーを設定できないことです。

+ +

Event インターフェイスへのアクセス

+ +

イベントハンドラーは (DOM 要素や文書、 {{domxref("window")}} オブジェクト等を含めた) 様々なオブジェクトに追加されるでしょう。イベントが発生すると、イベントオブジェクトが生成され順番にイベントリスナーが呼ばれます。

+ +

{{domxref("Event")}} インターフェイスは、イベントハンドラーの内部からアクセス可能で、第 1 引数としてイベントオブジェクトを介して渡されます。以下のシンプルな例は、イベントハンドラーにどのようにイベントオブジェクトが渡され、その中でどのように使われるかを示します。

+ +
function print(evt) {
+  // evt 引数は自動的にイベントオブジェクトに割り当てられます
+  // console.log と alert の違いに注意してください
+  console.log('print:', evt)
+  alert(evt)
+}
+// どの関数も意味を持つ適切な名前を付けてください
+table_el.onclick = print
+
+ + + + diff --git a/files/ja/orphaned/web/guide/events/event_handlers/index.html b/files/ja/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..7cdd63d81e --- /dev/null +++ b/files/ja/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,173 @@ +--- +title: DOM onevent ハンドラー +slug: orphaned/Web/Guide/Events/Event_handlers +tags: + - Beginner + - DOM + - DOM Beginner + - NeedsBeginnerUpdate + - NeedsUpdate +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

ウェブプラットフォームでは、DOM イベントの通知を受け取るための方法をいくつか提供しています。よく使われる方法は2つあり、 {{domxref("EventTarget.addEventListener", "addEventListener()")}} と、特定の onevent ハンドラーです。このページでは、後者がどのように機能するのかについて注目します。

+ +

onevent ハンドラーの登録

+ +

onevent ハンドラーは特定の DOM 要素のプロパティで、その要素がイベントに対してどのように反応するかを管理します。要素には、対話的なもの (リンク、ボタン、画像、フォームなど) と対話的ではないもの (基本の <body> 要素など) があります。イベントとは、以下のようなアクションのことです。

+ +
    +
  • クリックされた
  • +
  • キーの押下が検出された
  • +
  • フォーカスを受け取った
  • +
+ +

onevent ハンドラーは通常、onclick, onkeypress, onfocus など、反応するイベントに従って名前が付けられています。

+ +

on<…> イベントハンドラーを指定することで、指定されたオブジェクトの特定のイベント ({{event("click")}} など) に対してさまざまな方法で指定することができます。

+ +
    +
  • 要素に on<eventtype> という名前の HTML {{Glossary("attribute", "属性")}}を追加する方法。
    + <button onclick="handleClick()">,
  • +
  • または、JavaScript から対応する {{Glossary("property/JavaScript", "property")}} を設定する方法。
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

onevent イベントハンドラープロパティは、1 つのイベントハンドラーを割り当てることができる一種のプレースホルダーとして機能します。与えられたオブジェクト上の同じイベントに対して複数のハンドラーをインストールできるようにするには、その addEventListener() メソッドを呼び出して、オブジェクト上の与えられたイベントに対するハンドラーのリストを管理することができます。ハンドラーは、その {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} 関数を呼び出すことで、オブジェクトから削除することができます。

+ +

要素に適用されるイベントが発生すると、そのイベントハンドラーが次々と呼び出され、イベントを処理できるようになります。自分で呼び出す必要はありませんが、多くの場合、イベントの発生を簡単にシミュレートするために呼び出すことができます。例えば、ボタンオブジェクト myButton を指定した場合、 myButton.onclick(myEventObject) を実行することでイベントハンドラーを直接呼び出すことができます。イベントハンドラーがイベントオブジェクトからデータにアクセスしない場合は、 onclick() を呼び出すときにイベントを省略することができます。

+ +

これは、イベントハンドラーのいずれかがイベントオブジェクト自身に対して {{domxref("Event.stopPropagation", "stopPropagation()")}} を呼び出すことでイベントの処理を明示的に停止しない限り、すべてのハンドラーが呼び出されるまで続きます。

+ +

要素以外のオブジェクト

+ +

イベントハンドラーはまた、 {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }} などを含む、イベントを生成する多くの要素以外のオブジェクトのプロパティを使用して設定することもできます。例えば、 progress イベントが XMLHttpRequest のインスタンスで発生した場合は次のようになります。

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML の onevent 属性

+ +

HTML 要素には onevent という名前の属性があり、これを利用して HTML コード内に直接イベントのハンドラーを登録することができます。要素が HTML から構築されると、その onevent 属性の値がその要素を表す DOM オブジェクトにコピーされるので、JavaScript を使って属性の値にアクセスすると、HTML で設定された値が得られます。

+ + + +

HTML の属性値への更なる変更は {{domxref("Element/setAttribute", "setAttribute")}} メソッドで行うことができます。 JavaScript プロパティを変更しても効果あありません。

+ +

HTML

+ +

このような HTML 文書があったとします。

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

この JavaScript は、 HTML 属性の値が JavaScript オブジェクトのプロパティの変更によって影響を受けないことを示しています。

+ +
let logElement = document.querySelector('div');
+let el = document.querySelector("a");
+
+function log(msg) { logElement.innerHTML += `${msg}<br>` };
+function anchorOnClick(event) { log("Changed onclick handler") };
+
+// Original Handler
+log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
+
+//Changing handler using .onclick
+log('<br>Changing onclick handler using <strong> onclick property </strong> ');
+
+el.onclick = anchorOnClick;
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
+
+//Changing handler using .setAttribute
+log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
+el.setAttribute("onclick", 'anchorOnClick(event)');
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
+ +

結果

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

歴史的な理由から、{{HTMLElement("body")}} および {{HTMLElement("frameset")}} 要素の一部の属性/プロパティは、実際にはその親 {{domxref("Window")}} オブジェクトにイベントハンドラーを設定します。(HTML 仕様はこれらを {{domxref("GlobalEventHandlers/onblur", "onblur")}}, {{domxref("GlobalEventHandlers/onerror", "onerror")}}, {{domxref("GlobalEventHandlers/onfocus", "onfocus")}}, {{domxref("GlobalEventHandlers/onload", "onload")}}, {{domxref("GlobalEventHandlers/onscroll", "onscroll")}} と命名しています。)

+ +

イベントハンドラーの引数、this の結びつけ、および返値

+ +

イベントハンドラーが HTML 属性として指定されている場合、指定されたコードは次の引数を持つ関数にラップされます。

+ +
    +
  • event - {domxref("GlobalEventHandlers.onerror", "onerror")}} を除くすべてのイベントハンドラー。
  • +
  • event, source, lineno, colno, error - {{domxref("GlobalEventHandlers.onerror", "onerror")}} のイベントハンドラー。なお、 event 引数には、実際にはエラーメッセージが文字列として含まれています。
  • +
+ +

イベントハンドラーが呼び出されると、ハンドラー内の this キーワードは、ハンドラーが登録されている DOM 要素に設定されます。詳しくは、this キーワードのドキュメントを参照してください。

+ +

ハンドラーからの返値は、イベントが取り消されるかどうかを決定します。返値値の具体的な処理はイベントの種類によって異なります。詳細については、HTML 仕様の「イベントハンドラー処理アルゴリズム」を参照してください。

+ +

イベントハンドラーが呼び出されたとき

+ +
+

作成中 (非捕獲リスナー)

+
+ +

用語集

+ +

イベントハンドラーという用語は、次のように使用されます。

+ +
    +
  • イベントの通知を受けるように登録されている関数またはオブジェクト
  • +
  • または、より具体的には、<button onclick="alert(this)">window.onload = function() { … }など、HTML の on… 属性または Web API のプロパティを介してイベントリスナーを登録するメカニズム。
  • +
+ +

イベントを待ち受けするためのさまざまな方法を議論するときは、

+ +
    +
  • イベントリスナーは、{{domxref("EventTarget.addEventListener()")}} によって登録された関数またはオブジェクトを参照します。
  • +
  • 一方、イベントハンドラーon... 属性またはプロパティを介して登録された関数を指します。
  • +
+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

ブラウザーの互換性

+ +

イベントハンドラープロパティが存在することの検出

+ +

JavaScript の {{jsxref("Operators/in", "in")}} 演算子でイベントハンドラープロパティの存在を検出することができます。例えば、以下のようになります。

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

イベントハンドラーとプロトタイプ

+ +

DOM プロトタイプオブジェクトには、IDL で定義された属性の値を設定したり、アクセスしたりすることはできません。つまり、例えば Window.prototype.onload を変更することはできません。以前は、 Gecko では イベントハンドラー (onload など) が IDL 属性として実装されていなかったので可能だったのですが、現在はできなくなりました。これにより互換性が向上します。

diff --git a/files/ja/orphaned/web/guide/events/index.html b/files/ja/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..35f1c1184b --- /dev/null +++ b/files/ja/orphaned/web/guide/events/index.html @@ -0,0 +1,51 @@ +--- +title: イベント開発者ガイド +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +
{{draft()}}
+ +

イベントは、ウェブページの生存期間に起こる様々な出来事を非同期に扱うために使用されるデザインパターンと、さまざまな種類の多数の出来事についての名前、特性付け、利用の両方を指します。

+ +

概要ページでは、デザインパターンの紹介と最近のウェブブラウザーで定義され行われる出来事の種類の概要を提供します。

+ +

カスタムイベントページでは、独自コードでイベントコードのデザインパターンを使用して、ユーザーオブジェクトによって発行される新しいイベント型を定義し、それらのイベントを処理するためのリスナー関数を登録し、ユーザーのコードでイベントを発生させる方法について説明します。

+ +

その他のページでは、ウェブブラウザーで定義されているさまざまな種類のイベントの使用方法について説明します。残念なことに、これらのイベントはウェブブラウザーの進化に合わせて部分的に定義されてきたため、最新のウェブブラウザーに組み込まれている、または定義されているイベントの満足のいく体系的な特徴付けはありません。

+ +

ウェブブラウザーが実行されている端末は、例えば実世界での場所や方向の変化によってイベントが発生することがあり、これは方向座標系上のページおよび三次元変換の使用上のページで部分的に説明されているとおりです。これは端末の縦の方向が変化した場合とは異なりますが、似ています。

+ +

ブラウザーが表示されるウィンドウがイベントを発生させることがあります。例えば、ユーザーがウィンドウを最大化したり、その他の変更があったりすると、サイズ変更イベントが発生します。

+ +

ウェブページを読み込んでいるプロセスがユーザーに表示するためにウェブページをダウンロードし、解析し、レンダリングする様々な段階を補完するための応答としてイベントを発生することがあります。

+ +

ウェブページのコンテンツへのユーザーの操作がイベントを発生させることがあります。ユーザーの操作によって発生したイベントは、ブラウザー設計の初期の頃に進化し、イベントが呼び出される順序およびその順序を制御することができる方法を定義する複雑なシステムを含んでいます。さまざまな種類のユーザー対話型イベントには、以下のものがあります。

+ + + +

構造面やコンテンツにおけるウェブページの変更が、いくつかのイベントを発生させることがあり、変化イベントのページで説明されているとおりですが、これらのイベントはより軽い Mutation Observer のアプローチに置き換えられて非推奨になっています。

+ +

HTML 文書に埋め込まれたメディアストリームがいくつかのイベントを発生させることがあり、メディアイベントページで説明されている通りです。

+ +

ウェブページによって行われるネットワークリクエストが、いくつかのイベントを発生させることがあります。

+ +

他にも、ウェブブラウザーが定義したイベントの発生源で、このガイドではまだ言及していないものがたくさんあります。

+ +
+

メモ: このイベント開発者ガイドは継続的な作業が必要です。構造を再編したりページを書き直したりする必要があります。イベントについて知っておくことが必要なすべてをここで提供できるようになりたいと考えています。

+
+ +

文書

+ +

{{LandingPageListSubpages}}

diff --git a/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..637b1cc413 --- /dev/null +++ b/files/ja/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,50 @@ +--- +title: 方向および動きとして示されるデータ +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +tags: + - DOM + - Mobile + - Motion + - NeedsContent + - Orientation + - Responsive Design + - páginas_a_traducir + - rotation +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+

方向や動きのイベントを使用するときは、ブラウザから与えられる値の意味を理解することが重要です。この記事では操作時の座標システムに関する詳細情報と、それらの使い方を説明します。

+

座標フレームについて

+

{{原語併記("座標フレーム", "coordinate frame")}} は、オブジェクトに関する 3 軸 (X、Y、Z) の方向が定義されているシステムです。方向や動きのイベントを使用するときに考慮する座標フレームは 2 つあります:

+

地球座標フレーム

+

{{原語併記("地球座標フレーム", "Earth coordinate frame")}} は、地球の中心に固定されている座標フレームです。すなわち、軸は重力によって引かれる力および標準的な磁北方向に基づいて揃えられます。私たちは大文字 ("X"、"Y"、"Z") を、地球座標フレームの軸を示すために使用します。

+
    +
  • X 軸は地面に沿ってたどり、Y 軸と直交します。また、軸の正の方向が東を指します (従って、負の方向は西を指します)。
  • +
  • Y 軸は地面に沿ってたどり、正の方向が真北 (すなわち北極であり、磁北ではありません) を、負の方向が真南を指します。
  • +
  • Z 軸は地面に直交します。これは、デバイスと地球の中心との間に引かれた線と考えてください。Z 座標の値は正の方向が上向き (地球の中心から遠ざかる)、負の方向が下向き (地球の中心に向かう) です。
  • +
+

デバイス座標フレーム

+

{{原語併記("デバイス座標フレーム", "Device coordinate frame")}} は、デバイスの中心に固定された座標フレームです。私たちは小文字 ("x"、"y"、"z") を、デバイス座標フレームの軸を示すために使用します。

+

axes.png

+
    +
  • x 軸はスクリーンの水平面にあり、正の方向が右を、負の方向が左を指します。
  • +
  • y 軸はスクリーンの水平面にあり、正の方向が上端側を、負の方向が下端側を指します。
  • +
  • z 軸はスクリーンやキーボードに直交しており、正の方向がスクリーンから外側へ伸びていきます。
  • +
+
+ 注意: 電話機やタブレットでは、デバイスの方向が常にスクリーンの標準的な方向に対して考えられます。これは、ほとんどのデバイスで "ポートレート" 方向になります。ラップトップコンピュータでは、方向はキーボードに対して考えられます。補正するためにデバイスの方向の変化を検知したい場合は、orientationchange イベントを使用できます。
+

回転について

+

回転は、デバイス座標フレームと地球座標フレームとの度合いの違いという点から各軸で表現され、またそれは度単位で測られます

+

Alpha

+

z 軸を中心にした回転、すなわちデバイスをひねるようにすると、alpha 回転角が変化します:

+

alpha.png

+

alpha 角はデバイスの上端が地球の北極をまっすぐ向いているときが 0 度であり、デバイスが左へ回転するのに従って増加します。

+

Beta

+

x 軸を中心にした回転、すなわちデバイスを向こう側やユーザ側へ向かって傾けると、beta 回転角が変化します:

+

beta.png

+

beta 角はデバイスの上端および下端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを前方へ傾けるのに従って 180 度まで増加、後方へ傾けるのに従って -180 度まで減少します。

+

Gamma

+

y 軸を中心にした回転、すなわちデバイスを左右に傾けると、gamma 回転角が変化します:

+

gamma.png

+

gamma 角はデバイスの左端および右端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを右へ傾けるのに従って 90 度まで増加、左へ傾けるのに従って -90 度まで減少します。

diff --git a/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..4e30c38418 --- /dev/null +++ b/files/ja/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,137 @@ +--- +title: Overview of Events and Handlers +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +
+

This overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle.

+
+ +

Events and event handling provide a core technique in JavaScript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page,  relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.

+ +

Events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. Initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. The displayed page remains unchanged until the browser requests a new page. With the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. Event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which JavaScript leverages. (The talk is available from several sources, including this one.) Currently, all execution environments for JavaScript code use events and event handling.

+ +

The event design pattern

+ +

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

+ +
    +
  • the name String used for the event,
  • +
  • the type of the data structure used to represent the key properties of that event, and
  • +
  • the JavaScript object which will 'emit' that event.
  • +
+ +

The pattern is implemented by

+ +
    +
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • +
  • registering the function using the name String with the object which will emit the event.
  • +
+ +

The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using completely custom code, as explained in the article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

+ +

Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects.

+ +

Button Event Handler Demo

+ +

For example, browser button elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. We could define in the HTML page a button as:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

+ +
var example_click_handler = function (ev){
+    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
+    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
+};
+ +

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement JavaScript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

+ +
var funcInit = function(){
+    // user code goes here and can safely address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

+ +

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ +

 

+ +

The Event object hierarchy

+ +

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + + +

 

+ +

 

+ +

 

diff --git a/files/ja/web/api/detecting_device_orientation/index.html b/files/ja/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 8dc09fea8b..0000000000 --- a/files/ja/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: デバイスの方向の検出 -slug: Web/API/Detecting_device_orientation -tags: - - API - - Device Orientation - - Firefox OS - - Intermediate - - Mobile - - Motion - - Orientation - - Reference - - WebAPI -translation_of: Web/API/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

Web を利用可能なデバイスは、自身の方向を特定できるようになってきました。つまりデバイスは、重力との関係による自身の向きの変化を示すデータを報告できます。特に携帯電話のようなハンドヘルドデバイスは、表示内容が直立し続けるよう自動的に回転させるためにこの情報を使用でき、画面の幅が高さより大きくなるようにデバイスを回転させたときは、Web コンテンツをワイドスクリーン表示にします。

- -

方向の情報を制御する JavaScript イベントが 2 つあります。ひとつは {{domxref("DeviceOrientationEvent")}} であり、加速度センサーがデバイスの方向の変化を検出したときに発生します。Orientation イベントが報告するデータを受け取って処理することで、ユーザがデバイスを動かすことによる方向や高さの変化に対してインタラクティブに応答できるようになります。

- -

もうひとつのイベントは {{domxref("DeviceMotionEvent")}} であり、加速度が変化したときに発生します。こちらは方向ではなく加速度の変化を監視することが、{{domxref("DeviceOrientationEvent")}} との違いです。一般的に {{domxref("DeviceMotionEvent")}} を検出できるセンサーには、可動部があるストレージ装置を保護するためラップトップパソコンに内蔵するものも含みます。{{domxref("DeviceOrientationEvent")}} は、モバイルデバイスでとても一般的です。

- -

orientation イベントを処理する

- -

方向の変化を受け取り始めるには、{{event("deviceorientation")}} イベントをリッスンします:

- -
-

注記: gyronorm.js は、モバイルデバイスの加速度センサーやジャイロスコープのデータを正規化するためのポリフィルです。これは、デバイスの方向のサポート状況の違いを克服するのに役立ちます。

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

イベントリスナ (この例では handleOrientation() という名前の JavaScript 関数) を登録すると、リスナ関数は最新の方向データとともに、周期的に呼び出されます。

- -

Orientation イベントは 4 つの値を持ちます:

- -
    -
  • {{domxref("DeviceOrientationEvent.absolute")}}
  • -
  • {{domxref("DeviceOrientationEvent.alpha")}}
  • -
  • {{domxref("DeviceOrientationEvent.beta")}}
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}}
  • -
- -

イベントハンドラ関数は以下のようなものです:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // 新たな方向データに基づいて処理を行う
-}
-
- -

方向として示される値

- -

それぞれの軸で報告される値は、標準座標系の軸を中心にした回転量を表します。これらは方向および動きとして示されるデータの記事で詳しく説明しており、ここでは概要を記載します。

- -
    -
  • {{domxref("DeviceOrientationEvent.alpha")}} の値は z 軸を中心にしたデバイスの動きを表し、0 から 360 の範囲による度数で表されます。
  • -
  • {{domxref("DeviceOrientationEvent.beta")}} の値は x 軸を中心にしたデバイスの動きを表し、-180 から 180 の範囲の値による度数で表されます。これはデバイスの前後の動きです。
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}} の値は y 軸を中心にしたデバイスの動きを表し、-90 から 90 の範囲の値による度数で表されます。これはデバイスの左右の動きです。
  • -
- -

- -

このサンプルは方向を検出可能なデバイス上で、{{event("deviceorientation")}} イベントをサポートするブラウザを実行する場合に動作します。

- -

庭にボールがあると考えます:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

庭の幅は 200 ピクセルであり (小さな庭です)、ボールは中心にあります:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

デバイスを動かすと、その動きに応じてボールが移動します:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // -180 から 180 の範囲で角度を示す
-  var y = event.gamma; // -90 から 90 の範囲で角度を示す
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // デバイスをひっくり返したくはないため、
-  // x の値を -90 から 90 の範囲に制限する
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // 計算を容易にするため、x および y の値の範囲を
-  // 0 から 180 に変換する
-  x += 90;
-  y += 90;
-
-  // 10 は、ボールのサイズの半分である。
-  // これにより、配置場所をボールの中心に合わせる
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

結果を以下に示します:

- -
{{EmbedLiveSample('Orientation_example', '230', '260')}}
- -
-

警告: Chrome と Firefox では角度の扱い方が異なり、一部の軸の向きが逆になっています。

-
- -

motion イベントを処理する

- -

motion イベントは orientation イベントと同じ方法で扱えますが、イベント名は {{event("devicemotion")}} になります。

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

実際どのように変化したかの情報は、HandleMotion 関数のパラメータとして渡す {{domxref("DeviceMotionEvent")}} オブジェクトが提供します。

- -

motion イベントは 4 つのプロパティを持ちます:

- -
    -
  • {{domxref("DeviceMotionEvent.acceleration")}}
  • -
  • {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}}
  • -
  • {{domxref("DeviceMotionEvent.rotationRate")}}
  • -
  • {{domxref("DeviceMotionEvent.interval")}}
  • -
- -

動きとして示される値

- -

{{domxref("DeviceMotionEvent")}} オブジェクトは Web 開発者に、デバイスの位置や方向が変化した速度の情報を提供します。変化量は 3 つの軸 (詳しくは方向および動きとして示されるデータをご覧ください) に沿って表します。

- -

{{domxref("DeviceMotionEvent.acceleration","acceleration")}} および {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}} で対応する軸は以下のとおりです:

- -
    -
  • x: 西から東へ向かう軸を表します。
  • -
  • y: 南から北へ向かう軸を表します。
  • -
  • z: 地面から直立する軸を表します。
  • -
- -

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}} では状況が若干異なります。こちらの情報はそれぞれ以下のように対応します:

- -
    -
  • alpha: スクリーン (デスクトップ環境ではキーボード) から直立する軸を表します。
  • -
  • beta: スクリーンの面 (デスクトップ環境ではキーボード) の左から右へ向かう軸に沿った回転量を表します。
  • -
  • gamma: スクリーンの面 (デスクトップ環境ではキーボード) の下から上へ向かう軸に沿った回転量を表します。
  • -
- -

最後に {{domxref("DeviceMotionEvent.interval","interval")}} は、デバイスからデータを取得する間隔をミリ秒単位で表します。

- -

仕様

- - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}最初の仕様
- -

ブラウザ実装状況

- -
-

DeviceMotionEvent

- - - -

{{Compat("api.DeviceMotionEvent")}}

- -

DeviceOrientationEvent

- - - -

{{Compat("api.DeviceOrientationEvent")}}

-
- -

関連情報

- - diff --git a/files/ja/web/api/document_object_model/events/index.html b/files/ja/web/api/document_object_model/events/index.html deleted file mode 100644 index 1d8b1974a6..0000000000 --- a/files/ja/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: イベントと DOM -slug: Web/API/Document_Object_Model/Events -tags: - - DOM - - Guide - - ガイド -translation_of: Web/API/Document_Object_Model/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

はじめに

- -

この章では DOM のイベントモデルを説明します。この Event インターフェイス自身は、 DOM のノード上にイベントを登録する為のインターフェイスと同様であり、イベントリスナーであるとも言えます。いくつかの長い例は、様々な Event インターフェイスがどのように他と関連するかを示します。

- -

DOM レベル 3 イベントの原案に、DOM を通して 3 つのフェーズから構成されるイベントフローを明確に説明した素晴らしい説明図があります。

- -

また、イベントが DOM 内をどのように伝播するかについては更に詳細なコード例、例 5: イベント伝播 (propagation) を参照してください。

- -

イベントリスナーの登録

- -

DOM の要素にイベントハンドラーを登録する方法は 3 つあります。

- -

{{domxref("EventTarget.addEventListener")}}

- -
// myButton は button 要素だと仮定します
-myButton.addEventListener('click', greet, false);
-function greet(event){
-    // print and have a look at the event object
-    // always print arguments in case of overlooking any other arguments
-    console.log('greet:', arguments)
-    alert('hello world')
-}
-
- -

これが最近のウェブページで使われる方法です。

- -
-

注: Internet Explorer 6 から 8 はこの方法をサポートせず、 {{domxref("EventTarget.attachEvent")}} という似た API を代わりにサポートします。ブラウザー間の互換性を確保するには、数多くある JavaScript ライブラリのうちの一つを使用してください。

-
- -

さらに詳細を知りたい場合は {{domxref("EventTarget.addEventListener")}} のリファレンスを参照してください。

- -

HTML 属性

- -
<button onclick="alert('Hello world!')">
-
- -

HTML 属性に書かれたこの JavaScript コードには、 event 引数を通してイベントオブジェクトが渡されます。返値は HTML の仕様で定義された特別な方法で処理されます

- -
-

警告: この方法は避けてください。これはマークアップを増加させ、可読性を下げます。コンテンツと振る舞いが正しく分離されておらず、バグの発見が困難になります。

-
- -

DOM 要素のプロパティ

- -
// myButton は button 要素と仮定します
-myButton.onclick = function(event){alert('Hello world')}
-
- -

この関数は 1 つの event 引数を取るように定義できます。返り値は HTML の仕様で定義された特別な方法で処理されます

- -

この書き方の問題は、各要素の各イベント毎に 1 つだけしかハンドラーを設定できないことです。

- -

Event インターフェイスへのアクセス

- -

イベントハンドラーは (DOM 要素や文書、 {{domxref("window")}} オブジェクト等を含めた) 様々なオブジェクトに追加されるでしょう。イベントが発生すると、イベントオブジェクトが生成され順番にイベントリスナーが呼ばれます。

- -

{{domxref("Event")}} インターフェイスは、イベントハンドラーの内部からアクセス可能で、第 1 引数としてイベントオブジェクトを介して渡されます。以下のシンプルな例は、イベントハンドラーにどのようにイベントオブジェクトが渡され、その中でどのように使われるかを示します。

- -
function print(evt) {
-  // evt 引数は自動的にイベントオブジェクトに割り当てられます
-  // console.log と alert の違いに注意してください
-  console.log('print:', evt)
-  alert(evt)
-}
-// どの関数も意味を持つ適切な名前を付けてください
-table_el.onclick = print
-
- - - - diff --git a/files/ja/web/guide/events/event_handlers/index.html b/files/ja/web/guide/events/event_handlers/index.html deleted file mode 100644 index 5123afd667..0000000000 --- a/files/ja/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: DOM onevent ハンドラー -slug: Web/Guide/Events/Event_handlers -tags: - - Beginner - - DOM - - DOM Beginner - - NeedsBeginnerUpdate - - NeedsUpdate -translation_of: Web/Guide/Events/Event_handlers ---- -

ウェブプラットフォームでは、DOM イベントの通知を受け取るための方法をいくつか提供しています。よく使われる方法は2つあり、 {{domxref("EventTarget.addEventListener", "addEventListener()")}} と、特定の onevent ハンドラーです。このページでは、後者がどのように機能するのかについて注目します。

- -

onevent ハンドラーの登録

- -

onevent ハンドラーは特定の DOM 要素のプロパティで、その要素がイベントに対してどのように反応するかを管理します。要素には、対話的なもの (リンク、ボタン、画像、フォームなど) と対話的ではないもの (基本の <body> 要素など) があります。イベントとは、以下のようなアクションのことです。

- -
    -
  • クリックされた
  • -
  • キーの押下が検出された
  • -
  • フォーカスを受け取った
  • -
- -

onevent ハンドラーは通常、onclick, onkeypress, onfocus など、反応するイベントに従って名前が付けられています。

- -

on<…> イベントハンドラーを指定することで、指定されたオブジェクトの特定のイベント ({{event("click")}} など) に対してさまざまな方法で指定することができます。

- -
    -
  • 要素に on<eventtype> という名前の HTML {{Glossary("attribute", "属性")}}を追加する方法。
    - <button onclick="handleClick()">,
  • -
  • または、JavaScript から対応する {{Glossary("property/JavaScript", "property")}} を設定する方法。
    - document.querySelector("button").onclick = function(event) { … }.
  • -
- -

onevent イベントハンドラープロパティは、1 つのイベントハンドラーを割り当てることができる一種のプレースホルダーとして機能します。与えられたオブジェクト上の同じイベントに対して複数のハンドラーをインストールできるようにするには、その addEventListener() メソッドを呼び出して、オブジェクト上の与えられたイベントに対するハンドラーのリストを管理することができます。ハンドラーは、その {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} 関数を呼び出すことで、オブジェクトから削除することができます。

- -

要素に適用されるイベントが発生すると、そのイベントハンドラーが次々と呼び出され、イベントを処理できるようになります。自分で呼び出す必要はありませんが、多くの場合、イベントの発生を簡単にシミュレートするために呼び出すことができます。例えば、ボタンオブジェクト myButton を指定した場合、 myButton.onclick(myEventObject) を実行することでイベントハンドラーを直接呼び出すことができます。イベントハンドラーがイベントオブジェクトからデータにアクセスしない場合は、 onclick() を呼び出すときにイベントを省略することができます。

- -

これは、イベントハンドラーのいずれかがイベントオブジェクト自身に対して {{domxref("Event.stopPropagation", "stopPropagation()")}} を呼び出すことでイベントの処理を明示的に停止しない限り、すべてのハンドラーが呼び出されるまで続きます。

- -

要素以外のオブジェクト

- -

イベントハンドラーはまた、 {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }} などを含む、イベントを生成する多くの要素以外のオブジェクトのプロパティを使用して設定することもできます。例えば、 progress イベントが XMLHttpRequest のインスタンスで発生した場合は次のようになります。

- -
const xhr = new XMLHttpRequest();
-xhr.onprogress = function() { … };
- -

HTML の onevent 属性

- -

HTML 要素には onevent という名前の属性があり、これを利用して HTML コード内に直接イベントのハンドラーを登録することができます。要素が HTML から構築されると、その onevent 属性の値がその要素を表す DOM オブジェクトにコピーされるので、JavaScript を使って属性の値にアクセスすると、HTML で設定された値が得られます。

- - - -

HTML の属性値への更なる変更は {{domxref("Element/setAttribute", "setAttribute")}} メソッドで行うことができます。 JavaScript プロパティを変更しても効果あありません。

- -

HTML

- -

このような HTML 文書があったとします。

- -
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
-   <a onclick="log('Click!')">these three words</a>.
-</p>
-
-<div></div>
- -

JavaScript

- -

この JavaScript は、 HTML 属性の値が JavaScript オブジェクトのプロパティの変更によって影響を受けないことを示しています。

- -
let logElement = document.querySelector('div');
-let el = document.querySelector("a");
-
-function log(msg) { logElement.innerHTML += `${msg}<br>` };
-function anchorOnClick(event) { log("Changed onclick handler") };
-
-// Original Handler
-log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
-
-//Changing handler using .onclick
-log('<br>Changing onclick handler using <strong> onclick property </strong> ');
-
-el.onclick = anchorOnClick;
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
-
-//Changing handler using .setAttribute
-log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
-el.setAttribute("onclick", 'anchorOnClick(event)');
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
- -

結果

- -

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

- -

歴史的な理由から、{{HTMLElement("body")}} および {{HTMLElement("frameset")}} 要素の一部の属性/プロパティは、実際にはその親 {{domxref("Window")}} オブジェクトにイベントハンドラーを設定します。(HTML 仕様はこれらを {{domxref("GlobalEventHandlers/onblur", "onblur")}}, {{domxref("GlobalEventHandlers/onerror", "onerror")}}, {{domxref("GlobalEventHandlers/onfocus", "onfocus")}}, {{domxref("GlobalEventHandlers/onload", "onload")}}, {{domxref("GlobalEventHandlers/onscroll", "onscroll")}} と命名しています。)

- -

イベントハンドラーの引数、this の結びつけ、および返値

- -

イベントハンドラーが HTML 属性として指定されている場合、指定されたコードは次の引数を持つ関数にラップされます。

- -
    -
  • event - {domxref("GlobalEventHandlers.onerror", "onerror")}} を除くすべてのイベントハンドラー。
  • -
  • event, source, lineno, colno, error - {{domxref("GlobalEventHandlers.onerror", "onerror")}} のイベントハンドラー。なお、 event 引数には、実際にはエラーメッセージが文字列として含まれています。
  • -
- -

イベントハンドラーが呼び出されると、ハンドラー内の this キーワードは、ハンドラーが登録されている DOM 要素に設定されます。詳しくは、this キーワードのドキュメントを参照してください。

- -

ハンドラーからの返値は、イベントが取り消されるかどうかを決定します。返値値の具体的な処理はイベントの種類によって異なります。詳細については、HTML 仕様の「イベントハンドラー処理アルゴリズム」を参照してください。

- -

イベントハンドラーが呼び出されたとき

- -
-

作成中 (非捕獲リスナー)

-
- -

用語集

- -

イベントハンドラーという用語は、次のように使用されます。

- -
    -
  • イベントの通知を受けるように登録されている関数またはオブジェクト
  • -
  • または、より具体的には、<button onclick="alert(this)">window.onload = function() { … }など、HTML の on… 属性または Web API のプロパティを介してイベントリスナーを登録するメカニズム。
  • -
- -

イベントを待ち受けするためのさまざまな方法を議論するときは、

- -
    -
  • イベントリスナーは、{{domxref("EventTarget.addEventListener()")}} によって登録された関数またはオブジェクトを参照します。
  • -
  • 一方、イベントハンドラーon... 属性またはプロパティを介して登録された関数を指します。
  • -
- -

仕様書

- - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

ブラウザーの互換性

- -

イベントハンドラープロパティが存在することの検出

- -

JavaScript の {{jsxref("Operators/in", "in")}} 演算子でイベントハンドラープロパティの存在を検出することができます。例えば、以下のようになります。

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

イベントハンドラーとプロトタイプ

- -

DOM プロトタイプオブジェクトには、IDL で定義された属性の値を設定したり、アクセスしたりすることはできません。つまり、例えば Window.prototype.onload を変更することはできません。以前は、 Gecko では イベントハンドラー (onload など) が IDL 属性として実装されていなかったので可能だったのですが、現在はできなくなりました。これにより互換性が向上します。

diff --git a/files/ja/web/guide/events/index.html b/files/ja/web/guide/events/index.html deleted file mode 100644 index d05127c86a..0000000000 --- a/files/ja/web/guide/events/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: イベント開発者ガイド -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - events -translation_of: Web/Guide/Events ---- -
{{draft()}}
- -

イベントは、ウェブページの生存期間に起こる様々な出来事を非同期に扱うために使用されるデザインパターンと、さまざまな種類の多数の出来事についての名前、特性付け、利用の両方を指します。

- -

概要ページでは、デザインパターンの紹介と最近のウェブブラウザーで定義され行われる出来事の種類の概要を提供します。

- -

カスタムイベントページでは、独自コードでイベントコードのデザインパターンを使用して、ユーザーオブジェクトによって発行される新しいイベント型を定義し、それらのイベントを処理するためのリスナー関数を登録し、ユーザーのコードでイベントを発生させる方法について説明します。

- -

その他のページでは、ウェブブラウザーで定義されているさまざまな種類のイベントの使用方法について説明します。残念なことに、これらのイベントはウェブブラウザーの進化に合わせて部分的に定義されてきたため、最新のウェブブラウザーに組み込まれている、または定義されているイベントの満足のいく体系的な特徴付けはありません。

- -

ウェブブラウザーが実行されている端末は、例えば実世界での場所や方向の変化によってイベントが発生することがあり、これは方向座標系上のページおよび三次元変換の使用上のページで部分的に説明されているとおりです。これは端末の縦の方向が変化した場合とは異なりますが、似ています。

- -

ブラウザーが表示されるウィンドウがイベントを発生させることがあります。例えば、ユーザーがウィンドウを最大化したり、その他の変更があったりすると、サイズ変更イベントが発生します。

- -

ウェブページを読み込んでいるプロセスがユーザーに表示するためにウェブページをダウンロードし、解析し、レンダリングする様々な段階を補完するための応答としてイベントを発生することがあります。

- -

ウェブページのコンテンツへのユーザーの操作がイベントを発生させることがあります。ユーザーの操作によって発生したイベントは、ブラウザー設計の初期の頃に進化し、イベントが呼び出される順序およびその順序を制御することができる方法を定義する複雑なシステムを含んでいます。さまざまな種類のユーザー対話型イベントには、以下のものがあります。

- - - -

構造面やコンテンツにおけるウェブページの変更が、いくつかのイベントを発生させることがあり、変化イベントのページで説明されているとおりですが、これらのイベントはより軽い Mutation Observer のアプローチに置き換えられて非推奨になっています。

- -

HTML 文書に埋め込まれたメディアストリームがいくつかのイベントを発生させることがあり、メディアイベントページで説明されている通りです。

- -

ウェブページによって行われるネットワークリクエストが、いくつかのイベントを発生させることがあります。

- -

他にも、ウェブブラウザーが定義したイベントの発生源で、このガイドではまだ言及していないものがたくさんあります。

- -
-

メモ: このイベント開発者ガイドは継続的な作業が必要です。構造を再編したりページを書き直したりする必要があります。イベントについて知っておくことが必要なすべてをここで提供できるようになりたいと考えています。

-
- -

文書

- -

{{LandingPageListSubpages}}

diff --git a/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html b/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index 467800a0d6..0000000000 --- a/files/ja/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: 方向および動きとして示されるデータ -slug: Web/Guide/Events/Orientation_and_motion_data_explained -tags: - - DOM - - Mobile - - Motion - - NeedsContent - - Orientation - - Responsive Design - - páginas_a_traducir - - rotation -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained ---- -

{{ Draft() }}

-

方向や動きのイベントを使用するときは、ブラウザから与えられる値の意味を理解することが重要です。この記事では操作時の座標システムに関する詳細情報と、それらの使い方を説明します。

-

座標フレームについて

-

{{原語併記("座標フレーム", "coordinate frame")}} は、オブジェクトに関する 3 軸 (X、Y、Z) の方向が定義されているシステムです。方向や動きのイベントを使用するときに考慮する座標フレームは 2 つあります:

-

地球座標フレーム

-

{{原語併記("地球座標フレーム", "Earth coordinate frame")}} は、地球の中心に固定されている座標フレームです。すなわち、軸は重力によって引かれる力および標準的な磁北方向に基づいて揃えられます。私たちは大文字 ("X"、"Y"、"Z") を、地球座標フレームの軸を示すために使用します。

-
    -
  • X 軸は地面に沿ってたどり、Y 軸と直交します。また、軸の正の方向が東を指します (従って、負の方向は西を指します)。
  • -
  • Y 軸は地面に沿ってたどり、正の方向が真北 (すなわち北極であり、磁北ではありません) を、負の方向が真南を指します。
  • -
  • Z 軸は地面に直交します。これは、デバイスと地球の中心との間に引かれた線と考えてください。Z 座標の値は正の方向が上向き (地球の中心から遠ざかる)、負の方向が下向き (地球の中心に向かう) です。
  • -
-

デバイス座標フレーム

-

{{原語併記("デバイス座標フレーム", "Device coordinate frame")}} は、デバイスの中心に固定された座標フレームです。私たちは小文字 ("x"、"y"、"z") を、デバイス座標フレームの軸を示すために使用します。

-

axes.png

-
    -
  • x 軸はスクリーンの水平面にあり、正の方向が右を、負の方向が左を指します。
  • -
  • y 軸はスクリーンの水平面にあり、正の方向が上端側を、負の方向が下端側を指します。
  • -
  • z 軸はスクリーンやキーボードに直交しており、正の方向がスクリーンから外側へ伸びていきます。
  • -
-
- 注意: 電話機やタブレットでは、デバイスの方向が常にスクリーンの標準的な方向に対して考えられます。これは、ほとんどのデバイスで "ポートレート" 方向になります。ラップトップコンピュータでは、方向はキーボードに対して考えられます。補正するためにデバイスの方向の変化を検知したい場合は、orientationchange イベントを使用できます。
-

回転について

-

回転は、デバイス座標フレームと地球座標フレームとの度合いの違いという点から各軸で表現され、またそれは度単位で測られます

-

Alpha

-

z 軸を中心にした回転、すなわちデバイスをひねるようにすると、alpha 回転角が変化します:

-

alpha.png

-

alpha 角はデバイスの上端が地球の北極をまっすぐ向いているときが 0 度であり、デバイスが左へ回転するのに従って増加します。

-

Beta

-

x 軸を中心にした回転、すなわちデバイスを向こう側やユーザ側へ向かって傾けると、beta 回転角が変化します:

-

beta.png

-

beta 角はデバイスの上端および下端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを前方へ傾けるのに従って 180 度まで増加、後方へ傾けるのに従って -180 度まで減少します。

-

Gamma

-

y 軸を中心にした回転、すなわちデバイスを左右に傾けると、gamma 回転角が変化します:

-

gamma.png

-

gamma 角はデバイスの左端および右端から地球の表面までの距離がどちらも同じであるときが 0 度であり、デバイスを右へ傾けるのに従って 90 度まで増加、左へ傾けるのに従って -90 度まで減少します。

diff --git a/files/ja/web/guide/events/overview_of_events_and_handlers/index.html b/files/ja/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index 0a52f3b4c6..0000000000 --- a/files/ja/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Overview of Events and Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

This overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle.

-
- -

Events and event handling provide a core technique in JavaScript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page,  relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.

- -

Events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. Initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. The displayed page remains unchanged until the browser requests a new page. With the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. Event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

- -
A comparison of the sequential and event-driven browser load sequences.
- -

to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which JavaScript leverages. (The talk is available from several sources, including this one.) Currently, all execution environments for JavaScript code use events and event handling.

- -

The event design pattern

- -

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

- -
    -
  • the name String used for the event,
  • -
  • the type of the data structure used to represent the key properties of that event, and
  • -
  • the JavaScript object which will 'emit' that event.
  • -
- -

The pattern is implemented by

- -
    -
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • -
  • registering the function using the name String with the object which will emit the event.
  • -
- -

The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using completely custom code, as explained in the article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

- -

Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects.

- -

Button Event Handler Demo

- -

For example, browser button elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. We could define in the HTML page a button as:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

- -
var example_click_handler = function (ev){
-    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
-    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
-};
- -

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement JavaScript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

- -
var funcInit = function(){
-    // user code goes here and can safely address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

- -

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- -

 

- -

The Event object hierarchy

- -

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - - -

 

- -

 

- -

 

diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index b0905fe764..306d13b6fa 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -627,6 +627,7 @@ /ko/docs/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/XSLT/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations /ko/docs/Web/API/Boolean /ko/docs/Web/JavaScript/Reference/Global_Objects/Boolean /ko/docs/Web/API/Canvas_API/캔버스_튜토리얼 /ko/docs/Web/API/Canvas_API/Tutorial +/ko/docs/Web/API/Detecting_device_orientation /ko/docs/orphaned/Web/API/Detecting_device_orientation /ko/docs/Web/API/Document/defaultView/popstate_event /ko/docs/Web/API/Window/popstate_event /ko/docs/Web/API/Document/defaultView/resize_event /ko/docs/Web/API/Window/resize_event /ko/docs/Web/API/Document/drag_이벤트 /ko/docs/Web/API/Document/drag_event @@ -634,6 +635,7 @@ /ko/docs/Web/API/DocumentOrShadowRoot/activeElement /ko/docs/Web/API/Document/activeElement /ko/docs/Web/API/DocumentOrShadowRoot/getSelection /ko/docs/Web/API/Document/getSelection /ko/docs/Web/API/DocumentOrShadowRoot/styleSheets /ko/docs/Web/API/Document/styleSheets +/ko/docs/Web/API/Document_Object_Model/Events /ko/docs/orphaned/Web/API/Document_Object_Model/Events /ko/docs/Web/API/Document_Object_Model/Preface /ko/docs/Web/API/Document_Object_Model /ko/docs/Web/API/Document_Object_Model/소개 /ko/docs/Web/API/Document_Object_Model/Introduction /ko/docs/Web/API/Document_Object_Model/예제 /ko/docs/Web/API/Document_Object_Model/Examples @@ -803,7 +805,9 @@ /ko/docs/Web/Guide/CSS/Visual_formatting_model /ko/docs/Web/CSS/Visual_formatting_model /ko/docs/Web/Guide/DOM /ko/docs/conflicting/Web/API/Document_Object_Model /ko/docs/Web/Guide/DOM/Using_full_screen_mode /ko/docs/Web/API/Fullscreen_API +/ko/docs/Web/Guide/Events /ko/docs/orphaned/Web/Guide/Events /ko/docs/Web/Guide/Events/Creating_and_triggering_events /ko/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ko/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ko/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ko/docs/Web/Guide/HTML /ko/docs/Learn/HTML /ko/docs/Web/Guide/HTML/Content_Editable /ko/docs/Web/Guide/HTML/Editable_content /ko/docs/Web/Guide/HTML/컨텐트_카테고리 /ko/docs/Web/Guide/HTML/Content_categories @@ -1038,7 +1042,7 @@ /ko/docs/Web/참조/API /ko/docs/Web/Reference/API /ko/docs/WebAPI /ko/docs/conflicting/Web/API /ko/docs/WebAPI/Battery_Status /ko/docs/Web/API/Battery_Status_API -/ko/docs/WebAPI/Detecting_device_orientation /ko/docs/Web/API/Detecting_device_orientation +/ko/docs/WebAPI/Detecting_device_orientation /ko/docs/orphaned/Web/API/Detecting_device_orientation /ko/docs/WebAPI/Managing_screen_orientation /ko/docs/Web/API/CSS_Object_Model/Managing_screen_orientation /ko/docs/WebAPI/Network_Information /ko/docs/Web/API/Network_Information_API /ko/docs/WebAPI/Proximity /ko/docs/Web/API/Proximity_Events diff --git a/files/ko/_wikihistory.json b/files/ko/_wikihistory.json index cb8b655ecf..6e5d3b301d 100644 --- a/files/ko/_wikihistory.json +++ b/files/ko/_wikihistory.json @@ -3637,12 +3637,6 @@ "Channy" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-12-01T12:09:06.517Z", - "contributors": [ - "dink95" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2020-05-26T14:45:03.340Z", "contributors": [ @@ -8834,18 +8828,6 @@ "corps99" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:03:35.888Z", - "contributors": [ - "moolow" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-03-23T22:48:26.046Z", - "contributors": [ - "PineMt" - ] - }, "Web/Guide/HTML/Content_categories": { "modified": "2020-07-29T11:16:44.120Z", "contributors": [ @@ -17981,14 +17963,6 @@ "oohii" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2019-03-23T23:27:06.270Z", - "contributors": [ - "ingpdw", - "PillarLee", - "junho85" - ] - }, "Web/API/CSS_Object_Model/Managing_screen_orientation": { "modified": "2019-03-23T23:27:05.980Z", "contributors": [ @@ -18704,5 +18678,31 @@ "contributors": [ "cs09g" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2019-03-23T23:27:06.270Z", + "contributors": [ + "ingpdw", + "PillarLee", + "junho85" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-12-01T12:09:06.517Z", + "contributors": [ + "dink95" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:03:35.888Z", + "contributors": [ + "moolow" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-03-23T22:48:26.046Z", + "contributors": [ + "PineMt" + ] } } \ No newline at end of file diff --git a/files/ko/orphaned/web/api/detecting_device_orientation/index.html b/files/ko/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..1fd9fe3e91 --- /dev/null +++ b/files/ko/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,274 @@ +--- +title: 기기 방향 감지하기 +slug: orphaned/Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

요약

+ +

웹을 이용 가능한 기기들은 자신들의 방향을 알 수 있게 되었다. 즉, 중력과의 관계에서 자신의 방향의 변화를 나타내는 데이터를 알 수 있다는 뜻이다. 특히, 휴대 전화와 같이 손에 쥐고 쓸 수 있는 기기들은 이 정보를 화면을 수직으로 유지하기 위해 자동으로 회전시키는데 사용할 수 있고, 기기가 회전되어서 폭이 높이보다 길 때는 와이드 스크린으로 표시할 수 있게 된다.

+ +

방향 정보를 다루는 두 가지 방법의 JavaScript 이벤트가 있다. 첫 번째는 {{domxref("DeviceOrientationEvent")}}로 가속도계가 기기의 방향의 변화를 감지했을 때 발생한다.  이 방향 이벤트들에 의해 보고되는 데이터를 받아서 처리함으로써, 사용자들이 기기를 움직이여서 생기는 방향과 높이의 변화를 상호 작용적으로 응답할 수 있게 된다.

+ +

두 번째 이벤트는 {{domxref("DeviceMotionEvent")}}로 가속도에 변화가 일어났을 때 발생한다. 이 이벤트는 {{domxref("DeviceOrientationEvent")}}와는 방향이 아닌 가속도를 감지하고 있다는 점에서 다르다. 일반적으로{{domxref("DeviceMotionEvent")}}를 감지할 수 있는 센서들은 저장 장치들을 충격으로부터 보호하기 위해 노트북에서 사용되는 센서들을 포함한다. {{domxref("DeviceOrientationEvent")}}는 모바일 기기에서 주로 더 많이 나타난다.

+ +

방향 이벤트 처리하기

+ +

방향의 변화를 받기 위해 여러분이 해야하는 것은 {{ event("deviceorientation") }} 이벤트에 리스너를 등록하는 것 뿐이다:

+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

이벤트 리스너를 등록한 후에는 (여기에서는 JavaScript 함수 handleOrientation()), 리스너 함수가 업데이트 된 방향 데이터와 함께 주기적으로 호출된다.

+ +

방향 이벤트는 다음 네 개의 값을 가진다:

+ +
    +
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • +
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • +
+ +

이벤트 핸들러 함수는 보통 다음과 같다:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

방향 값 설명

+ +

각 축으로부터 보고된 값은 표준 좌표계 축을 중심으로 회전한 양을 가리킨다. 더 자세한 내용은 Orientation and motion data explained 문서에 나와있으며, 다음은 이를 간략하게 요약한 것이다.

+ +
    +
  • {{ domxref("DeviceOrientationEvent.alpha") }} 값은 0도부터 360도까지 범위의 z축을 중심으로 한 기기의 움직임을 나타낸다.
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }} 값은 -180도부터 180도까지 범위의 x축을 줌심으로 한 기기의 움직임을 나타낸다. 이는 기기의 앞뒤 움직임을 나타낸다.
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }} 값은 -90도부터 90도까지 범위의 y축을 중심으로 한 기기의 움직임을 나타낸다. 이는 기기의 좌우 움직임을 나타낸다.
  • +
+ +

방향 예제

+ +

이 예제는 {{event("deviceorientation")}} 이벤트를 지원하고 방향을 감지할 수 있는 기기에서 실행중인 모든 브라우저에서 작동한다.

+ +

자 그럼, 정원에 공이 하나 있다고 상상해보자:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

이 정원은 가로 세로 200 픽셀이고(그렇다, 작은 정원이다), 정 중앙에 공이 있다:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

이제, 우리가 기기를 움직이면 공도 따라서 움직일 것이다:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positionning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

여기 실제로 실행해 볼 수 있는 예제이다:

+ +
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
+ +
+

경고: Chrome과 Firefox는 동일한 방식으로 각을 다루지 않습니다. 그래서 어떤 축의 방향은 반대가 됩니다.

+
+ +

모션 이벤트 처리하기

+ +

모션 이벤트는 이벤트 이름이 {{ event("devicemotion") }}으로 다르다는 점을 제외하면, 방향 이벤트를 처리하는 방법과 동일하다.

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

HandleMotion 함수의 파라미터로 넘겨진 {{ domxref("DeviceMotionEvent") }} 객체에 실제로 변화된 정보들이 담겨져 있다.

+ +

모션 이벤트는 다음 네 가지 속성을 가진다:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

모션 값 설명

+ +

{{ domxref("DeviceMotionEvent") }} 객체는 웹 개발자들에게 기기의 위치와 방향의 변화 속도에 관한 정보를 제공한다. 세 개의 축에 따라 변화한 정보가 제공된다 (자세한 내용은 Orientation and motion data explained 문서를 참조).

+ +

{{domxref("DeviceMotionEvent.acceleration","acceleration")}}과 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}에서, 각 축은 다음에 해당된다:

+ +
    +
  • x: 서쪽에서 동쪽으로 나타나는 축을 의미한다
  • +
  • y: 남쪽에서 북쪽으로 나타나는 축을 의미한다
  • +
  • z: 땅에서 수직으로 나타나는 축을 의미한다
  • +
+ +

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}에서, 조금은 다르게, 각 값들은 다음에 해당된다:

+ +
    +
  • alpha: 화면(또는 데스크탑의 키보드)에 수직인 축을 따른 회전율을 의미한다
  • +
  • beta: 화면(또는 데스크탑의 키보드)의 평면의 왼쪽에서 오른쪽으로 나타나는 축을 따른 회전율을 의미한다
  • +
  • gamma: 화면(또는 데스크탑의 키보드)의 평면의 아래에서 위쪽으로 나타나는 축을 따른 회전율을 의미한다
  • +
+ +

마지막으로, {{domxref("DeviceMotionEvent.interval","interval")}}은 기기에서 데이터를 얻을 수 있는 시간 간격(단위는 밀리초)을 의미한다.

+ +

스펙

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

브라우저 호환성

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
+ 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
+ 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}4.2
+
+ +

Gecko 구현 참고 사항

+ +
    +
  1. Firefox 3.6, 4, 5는 표준인 {{domxref("DeviceOrientationEvent")}} 이벤트가 아닌 mozOrientation 을 지원한다
  2. +
+ +

참고 자료

+ + diff --git a/files/ko/orphaned/web/api/document_object_model/events/index.html b/files/ko/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..84152bbfbc --- /dev/null +++ b/files/ko/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,85 @@ +--- +title: Events and the DOM +slug: orphaned/Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +
{{DefaultAPISidebar("DOM")}}
+ +

소개

+ +

이 장에서는 DOM 이벤트 모델을 설명한다.  Event 인터페이스는 DOM의 노드에서 이벤트 등록 및  event listeners를 위한 인터페이스와 더불어 다양한 이벤트 인터페이스가 서로 어떻게 관련되는지 보여주는 몇 가지 더 긴 예와 함께 설명된다.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Event listener등록

+ +

DOM 요소에 대한 이벤트 핸들러를 등록하는 방법에는 3가지가 있다.

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', greet, false)
+function greet(event){
+    // print and have a look at the event object
+    // always print arguments in case of overlooking any other arguments
+    console.log('greet:', arguments)
+    alert('hello world')
+}
+
+ +

이 방식은 근대의 웹페이지에서 사용해야하는 방법이다.

+ +
+

Note: Internet Explorer 6–8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility, use one of the many JavaScript libraries available.

+
+ +

더 자세한 내용은{{domxref("EventTarget.addEventListener")}}를 참조하세요.

+ +

HTML 속성

+ +
<button onclick="alert('Hello world!')">
+
+ +

속성에서 JavaScript 코드는 이벤트 매개변수를 통해 이벤트 객체를 통과합니다. 반환 값은 HTML 사양에 설명된 특별한 방법으로 처리됩니다.

+ +
+

경고: 이 방법은 피해야 합니다! 그것은 마크업을 부풀리고, 읽기 어렵게 만듭니다. 내용/구조와 행동에 대한 우려는 잘 분리되어 있지 않아 버그를 찾기가 더 어려워집니다.

+
+ +

DOM 요소 특성

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects (including DOM elements, document, the {{domxref("window")}} object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
function print(evt) {
+  // the evt parameter is automatically assigned the event object
+  // take care of the differences between console.log & alert
+  console.log('print:', evt)
+  alert(evt)
+}
+// any function should have an appropriate name, that's what called semantic
+table_el.onclick = print
+
+ + + + diff --git a/files/ko/orphaned/web/guide/events/index.html b/files/ko/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..596c7f932d --- /dev/null +++ b/files/ko/orphaned/web/guide/events/index.html @@ -0,0 +1,52 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsUpdate + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+ +

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+ +

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..3690555d42 --- /dev/null +++ b/files/ko/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,143 @@ +--- +title: Overview of Events and Handlers +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +
+

 이 글은 이벤트 및 이벤트 핸들링(event handling)에 대한 개요로서, 웹 페이지가 열려있는 동안 일어나는 사건(incident)에 대해 반응할 수 있도록 하는 코드 설계 패턴에 대해 설명하고, 현 세대의 웹 브라우저에서 핸들링할 수 있는 사건의 종류에 대해 요약한다.

+
+ +

 이벤트와 이벤트 핸들링은 웹 페이지가 사용자에 의해 열린 상태를 유지하는 동안 일어나는 사건에 대한 반응을 구현하기 위한 자바스크립트의 핵심적인 기술이다. 이러한 사건에는 페이지가 전시(display)되기 위한 준비과정 중 일어나는 사건, 웹 페이지상의 컨텐츠와 사용자의 상호작용에 의한 사건, 브라우저가 실행되는 기반 장치와 관련된 사건, 매체 스트림(media stream) 재생이나 애니메이션 시간 간격 등 기타 요인에 의한 사건 등이 있다.

+ +

 이벤트와 이벤트 핸들링은 자바스크립트가 처음 도입된 시점부터 중심적인 역할을 했으며, 이와 함께 브라우저의 렌더링 아키텍처 역시 단일 처리경로(single pass) 페이지 렌더링으로부터 리플로우(reflow) 기반, 이벤트 구동식(driven) 페이지 렌더링 개념으로 바뀌었다.

+ +

 최초에는 브라우저는 페이지의 모든 부분에 대한 문법분석(parse), 처리(process), 그리기(draw) 및 사용자에게 표현(present)까지의 모든 과정이 끝날 때까지 대기하고, 페이지 작업이 끝나면 그 상태로 바뀌지 않고 새 페이지 요청이 있어서 가져오기(fetch)작업이 일어나기 전까지는 그대로의 모습을 유지했다. 

+ +

 리플로우 기반 이벤트 구동식 페이지 렌더링 개념으로 바뀐 뒤에는 브라우저는 처리, 그리기, 컨텐츠 표현(present), 반복순환작업을 다시 개시하도록 하는 이벤트 트리거에 대한 대기 등의 작업을 반복순환(loop)하여 수행한다. 이 이벤트 트리거라는 것은 이벤트를 발생하게 하는 사건을 이르는 것으로서, 네트워크상의 자원 로드 완료( 예 : 이미지가 다운로드되어 화면상에 그릴 수 있게 됨), 브라우저에 의한 자원의 문법분석 완료( 예 : HTML페이지 처리가 끝남) 페이지의 컨텐츠와 사용자와의 상호작용(예 : 버튼을 클릭한다) 등이 이러한 사건이 될 수 있다.

+ +

 더글라스 크록포드는 An inconvenient API : The theory of the DOM(불편한 API : DOM의 이론)이라는 제목의 강연에서 이러한 변화를 여러 단원에 걸쳐 설명하였는데, 본래의 작업 흐름에서 이벤트 구동식 브라우저의 작업 흐름으로 바뀌는 것을 다음과 같이 보여주었다.

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

 두 번째 그림에 보이는 처리방식은 마지막 단계의 작업흐름을 변화시킴으로써 첫 번째 그림의 단일 경로 처리흐름에서 반복순환 흐름으로 바뀐 것을 보여준다. 두 번째 그림은 Paint작업이 끝나면 새로운 이벤트 발생에 대한 처리(이벤트 핸들링)를 하기 위해 이벤트를 기다리게 된다. 이 혁신적인 개념을 이용하면 자원을 다 획득하지 않았더라도 페이지를 부분적으로 렌더링하는 것이 가능하며, 최초에는 자바스크립트에 의해 발전된 이벤트 구동에 의한 동작 효과적으로 구현할 수 있다. (이 강의는 여기를 포함한 다양한 경로로 볼 수 있다) 현재 모든 자바스크립트 코드 실행 환경에서는 이벤트와 이벤트 핸들링을 사용한다.

+ +

이벤트 설계 패턴

+ +

이벤트 시스템은 근본적으로는 단순한 프로그래밍 설계 패턴이다. 이 패턴는 기본적으로 이벤트의 종류와 다음 사항에 대해 합의된 약속을 기반으로 한다.

+ +
    +
  • 각 이벤트를 가리키는 이벤트명 문자열
  • +
  • 각 이벤트의 핵심 프로퍼티를 나타내기 위한 자료구조의 형식
  • +
  • 각 이벤트를 발동할 자바스크립트 객체
  • +
+ +

패턴을 구현하기 위해서는 다음이 필요하다.

+ +
    +
  • 위에서 약속된 자료구조를 인수로 받는 자바스크립트 함수를 정의한다.
  • +
  • 이벤트를 발동할 객체에 약속된 해당 이벤트의 이벤트명을 사용하여 위의 함수를 등록한다.
  • +
+ +

이 함수는 리스너(listener) 또는 핸들러(handler)라는 혼용된 명칭으로 불린다. 이 패턴은 커스텀 이벤트에 관한 글에서 설명한 대로의 완전한 커스텀 이벤트를 사용하여 쉽게 구현할 수 있다. 이 패턴은 사용자 입력, 브라우저 활동 등에 의해 발동되는 다양한 이벤트를 정의하는 최신 웹 브라우저에서도 많이 사용한다.

+ +

 최신 웹 브라우저는 이 이벤트 패턴을 표준화된 방식으로 구현한다. 브라우저는 어떤 이벤트의 프로퍼티를 나타내는 자료 구조로서  EventPrototype 객체를 원천으로 하는 어떤 객체를 사용한다. 또한 이러한 자료구조를 핸들링할 함수에 대한 등록 메소드로서 addEventListener 메소드를 사용하는데 이것은 인수로서 이벤트명과 핸들러 함수를 받는다. 마지막으로 브라우저는 이벤트 발동자(emitter)로 수많은 객체를 정의하며 또한 이 객체들에 의해 생성되는 여러 이벤트형(event type)을 정의한다.

+ +

버튼 이벤트 핸들러 데모

+ +

하나의 예시로서 브라우저 button 요소(element)는 'click'이라는 이름의 이벤트를 마우스 클릭 또는 터치스크린의 경우 손가락 터치에 반응하여 발동시킨다. 버튼은 HTML 페이지에서 다음과 같이 정의할 수 있다.

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

그리고 자바스크립트 코드에서 'click' 이벤트에 대한 리스너로서의 함수, 즉 핸들러로 사용할 함수를 정의한다.

+ +
var example_click_handler = function (ev){
+    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
+    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
+};
+ +

그 다음 해당 Button 객체와 함께 위의 함수를 등록하는데, 첫 번째 방법은 HTML 페이지의 DOM(문서 객체 모델) 표현법을 이용하여 다음과 같이 스크립트상에서 나타내는 방법이다. 

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

또 다른 방법은 HTML 페이지 상에서 'onclick' 애트리뷰트의 값으로 핸들러로 쓸 함수를 대입시키는 것인데, 보통 이 방식은 매우 단순한 웹 페이지에서나 쓰인다.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement Javascript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

As a second example, much modern Javascript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

+ +
var funcInit = function(){
+    // user code goes here and can safetly address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

+ +

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: This list of will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ +

 

+ +

The Event object hierarchy

+ +

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + + +

 

+ +

 

+ +

 

diff --git a/files/ko/web/api/detecting_device_orientation/index.html b/files/ko/web/api/detecting_device_orientation/index.html deleted file mode 100644 index 995997b5ab..0000000000 --- a/files/ko/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: 기기 방향 감지하기 -slug: Web/API/Detecting_device_orientation -translation_of: Web/API/Detecting_device_orientation -original_slug: WebAPI/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

요약

- -

웹을 이용 가능한 기기들은 자신들의 방향을 알 수 있게 되었다. 즉, 중력과의 관계에서 자신의 방향의 변화를 나타내는 데이터를 알 수 있다는 뜻이다. 특히, 휴대 전화와 같이 손에 쥐고 쓸 수 있는 기기들은 이 정보를 화면을 수직으로 유지하기 위해 자동으로 회전시키는데 사용할 수 있고, 기기가 회전되어서 폭이 높이보다 길 때는 와이드 스크린으로 표시할 수 있게 된다.

- -

방향 정보를 다루는 두 가지 방법의 JavaScript 이벤트가 있다. 첫 번째는 {{domxref("DeviceOrientationEvent")}}로 가속도계가 기기의 방향의 변화를 감지했을 때 발생한다.  이 방향 이벤트들에 의해 보고되는 데이터를 받아서 처리함으로써, 사용자들이 기기를 움직이여서 생기는 방향과 높이의 변화를 상호 작용적으로 응답할 수 있게 된다.

- -

두 번째 이벤트는 {{domxref("DeviceMotionEvent")}}로 가속도에 변화가 일어났을 때 발생한다. 이 이벤트는 {{domxref("DeviceOrientationEvent")}}와는 방향이 아닌 가속도를 감지하고 있다는 점에서 다르다. 일반적으로{{domxref("DeviceMotionEvent")}}를 감지할 수 있는 센서들은 저장 장치들을 충격으로부터 보호하기 위해 노트북에서 사용되는 센서들을 포함한다. {{domxref("DeviceOrientationEvent")}}는 모바일 기기에서 주로 더 많이 나타난다.

- -

방향 이벤트 처리하기

- -

방향의 변화를 받기 위해 여러분이 해야하는 것은 {{ event("deviceorientation") }} 이벤트에 리스너를 등록하는 것 뿐이다:

- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

이벤트 리스너를 등록한 후에는 (여기에서는 JavaScript 함수 handleOrientation()), 리스너 함수가 업데이트 된 방향 데이터와 함께 주기적으로 호출된다.

- -

방향 이벤트는 다음 네 개의 값을 가진다:

- -
    -
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • -
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • -
- -

이벤트 핸들러 함수는 보통 다음과 같다:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

방향 값 설명

- -

각 축으로부터 보고된 값은 표준 좌표계 축을 중심으로 회전한 양을 가리킨다. 더 자세한 내용은 Orientation and motion data explained 문서에 나와있으며, 다음은 이를 간략하게 요약한 것이다.

- -
    -
  • {{ domxref("DeviceOrientationEvent.alpha") }} 값은 0도부터 360도까지 범위의 z축을 중심으로 한 기기의 움직임을 나타낸다.
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }} 값은 -180도부터 180도까지 범위의 x축을 줌심으로 한 기기의 움직임을 나타낸다. 이는 기기의 앞뒤 움직임을 나타낸다.
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }} 값은 -90도부터 90도까지 범위의 y축을 중심으로 한 기기의 움직임을 나타낸다. 이는 기기의 좌우 움직임을 나타낸다.
  • -
- -

방향 예제

- -

이 예제는 {{event("deviceorientation")}} 이벤트를 지원하고 방향을 감지할 수 있는 기기에서 실행중인 모든 브라우저에서 작동한다.

- -

자 그럼, 정원에 공이 하나 있다고 상상해보자:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

이 정원은 가로 세로 200 픽셀이고(그렇다, 작은 정원이다), 정 중앙에 공이 있다:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

이제, 우리가 기기를 움직이면 공도 따라서 움직일 것이다:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positionning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

여기 실제로 실행해 볼 수 있는 예제이다:

- -
{{ EmbedLiveSample('Orientation_example', '230', '260') }}
- -
-

경고: Chrome과 Firefox는 동일한 방식으로 각을 다루지 않습니다. 그래서 어떤 축의 방향은 반대가 됩니다.

-
- -

모션 이벤트 처리하기

- -

모션 이벤트는 이벤트 이름이 {{ event("devicemotion") }}으로 다르다는 점을 제외하면, 방향 이벤트를 처리하는 방법과 동일하다.

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

HandleMotion 함수의 파라미터로 넘겨진 {{ domxref("DeviceMotionEvent") }} 객체에 실제로 변화된 정보들이 담겨져 있다.

- -

모션 이벤트는 다음 네 가지 속성을 가진다:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

모션 값 설명

- -

{{ domxref("DeviceMotionEvent") }} 객체는 웹 개발자들에게 기기의 위치와 방향의 변화 속도에 관한 정보를 제공한다. 세 개의 축에 따라 변화한 정보가 제공된다 (자세한 내용은 Orientation and motion data explained 문서를 참조).

- -

{{domxref("DeviceMotionEvent.acceleration","acceleration")}}과 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}}에서, 각 축은 다음에 해당된다:

- -
    -
  • x: 서쪽에서 동쪽으로 나타나는 축을 의미한다
  • -
  • y: 남쪽에서 북쪽으로 나타나는 축을 의미한다
  • -
  • z: 땅에서 수직으로 나타나는 축을 의미한다
  • -
- -

{{domxref("DeviceMotionEvent.rotationRate","rotationRate")}}에서, 조금은 다르게, 각 값들은 다음에 해당된다:

- -
    -
  • alpha: 화면(또는 데스크탑의 키보드)에 수직인 축을 따른 회전율을 의미한다
  • -
  • beta: 화면(또는 데스크탑의 키보드)의 평면의 왼쪽에서 오른쪽으로 나타나는 축을 따른 회전율을 의미한다
  • -
  • gamma: 화면(또는 데스크탑의 키보드)의 평면의 아래에서 위쪽으로 나타나는 축을 따른 회전율을 의미한다
  • -
- -

마지막으로, {{domxref("DeviceMotionEvent.interval","interval")}}은 기기에서 데이터를 얻을 수 있는 시간 간격(단위는 밀리초)을 의미한다.

- -

스펙

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
- -

브라우저 호환성

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.03.6[1]
- 6
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.03.6[1]
- 6
{{ CompatNo() }}{{ CompatNo() }}4.2
{{domxref("DeviceMotionEvent")}}{{ CompatVersionUnknown() }}6{{ CompatUnknown() }}{{ CompatUnknown() }}4.2
-
- -

Gecko 구현 참고 사항

- -
    -
  1. Firefox 3.6, 4, 5는 표준인 {{domxref("DeviceOrientationEvent")}} 이벤트가 아닌 mozOrientation 을 지원한다
  2. -
- -

참고 자료

- - diff --git a/files/ko/web/api/document_object_model/events/index.html b/files/ko/web/api/document_object_model/events/index.html deleted file mode 100644 index 2974c9d435..0000000000 --- a/files/ko/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Events and the DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

소개

- -

이 장에서는 DOM 이벤트 모델을 설명한다.  Event 인터페이스는 DOM의 노드에서 이벤트 등록 및  event listeners를 위한 인터페이스와 더불어 다양한 이벤트 인터페이스가 서로 어떻게 관련되는지 보여주는 몇 가지 더 긴 예와 함께 설명된다.

- -

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

- -

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

- -

Event listener등록

- -

DOM 요소에 대한 이벤트 핸들러를 등록하는 방법에는 3가지가 있다.

- -

{{domxref("EventTarget.addEventListener")}}

- -
// Assuming myButton is a button element
-myButton.addEventListener('click', greet, false)
-function greet(event){
-    // print and have a look at the event object
-    // always print arguments in case of overlooking any other arguments
-    console.log('greet:', arguments)
-    alert('hello world')
-}
-
- -

이 방식은 근대의 웹페이지에서 사용해야하는 방법이다.

- -
-

Note: Internet Explorer 6–8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility, use one of the many JavaScript libraries available.

-
- -

더 자세한 내용은{{domxref("EventTarget.addEventListener")}}를 참조하세요.

- -

HTML 속성

- -
<button onclick="alert('Hello world!')">
-
- -

속성에서 JavaScript 코드는 이벤트 매개변수를 통해 이벤트 객체를 통과합니다. 반환 값은 HTML 사양에 설명된 특별한 방법으로 처리됩니다.

- -
-

경고: 이 방법은 피해야 합니다! 그것은 마크업을 부풀리고, 읽기 어렵게 만듭니다. 내용/구조와 행동에 대한 우려는 잘 분리되어 있지 않아 버그를 찾기가 더 어려워집니다.

-
- -

DOM 요소 특성

- -
// Assuming myButton is a button element
-myButton.onclick = function(event){alert('Hello world')}
-
- -

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

- -

The problem with this method is that only one handler can be set per element and per event.

- -

Accessing Event interfaces

- -

Event handlers may be attached to various objects (including DOM elements, document, the {{domxref("window")}} object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.

- -

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

- -
function print(evt) {
-  // the evt parameter is automatically assigned the event object
-  // take care of the differences between console.log & alert
-  console.log('print:', evt)
-  alert(evt)
-}
-// any function should have an appropriate name, that's what called semantic
-table_el.onclick = print
-
- - - - diff --git a/files/ko/web/guide/events/index.html b/files/ko/web/guide/events/index.html deleted file mode 100644 index e952840d8e..0000000000 --- a/files/ko/web/guide/events/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsUpdate - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/ko/web/guide/events/overview_of_events_and_handlers/index.html b/files/ko/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index c3f1a9205a..0000000000 --- a/files/ko/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Overview of Events and Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

 이 글은 이벤트 및 이벤트 핸들링(event handling)에 대한 개요로서, 웹 페이지가 열려있는 동안 일어나는 사건(incident)에 대해 반응할 수 있도록 하는 코드 설계 패턴에 대해 설명하고, 현 세대의 웹 브라우저에서 핸들링할 수 있는 사건의 종류에 대해 요약한다.

-
- -

 이벤트와 이벤트 핸들링은 웹 페이지가 사용자에 의해 열린 상태를 유지하는 동안 일어나는 사건에 대한 반응을 구현하기 위한 자바스크립트의 핵심적인 기술이다. 이러한 사건에는 페이지가 전시(display)되기 위한 준비과정 중 일어나는 사건, 웹 페이지상의 컨텐츠와 사용자의 상호작용에 의한 사건, 브라우저가 실행되는 기반 장치와 관련된 사건, 매체 스트림(media stream) 재생이나 애니메이션 시간 간격 등 기타 요인에 의한 사건 등이 있다.

- -

 이벤트와 이벤트 핸들링은 자바스크립트가 처음 도입된 시점부터 중심적인 역할을 했으며, 이와 함께 브라우저의 렌더링 아키텍처 역시 단일 처리경로(single pass) 페이지 렌더링으로부터 리플로우(reflow) 기반, 이벤트 구동식(driven) 페이지 렌더링 개념으로 바뀌었다.

- -

 최초에는 브라우저는 페이지의 모든 부분에 대한 문법분석(parse), 처리(process), 그리기(draw) 및 사용자에게 표현(present)까지의 모든 과정이 끝날 때까지 대기하고, 페이지 작업이 끝나면 그 상태로 바뀌지 않고 새 페이지 요청이 있어서 가져오기(fetch)작업이 일어나기 전까지는 그대로의 모습을 유지했다. 

- -

 리플로우 기반 이벤트 구동식 페이지 렌더링 개념으로 바뀐 뒤에는 브라우저는 처리, 그리기, 컨텐츠 표현(present), 반복순환작업을 다시 개시하도록 하는 이벤트 트리거에 대한 대기 등의 작업을 반복순환(loop)하여 수행한다. 이 이벤트 트리거라는 것은 이벤트를 발생하게 하는 사건을 이르는 것으로서, 네트워크상의 자원 로드 완료( 예 : 이미지가 다운로드되어 화면상에 그릴 수 있게 됨), 브라우저에 의한 자원의 문법분석 완료( 예 : HTML페이지 처리가 끝남) 페이지의 컨텐츠와 사용자와의 상호작용(예 : 버튼을 클릭한다) 등이 이러한 사건이 될 수 있다.

- -

 더글라스 크록포드는 An inconvenient API : The theory of the DOM(불편한 API : DOM의 이론)이라는 제목의 강연에서 이러한 변화를 여러 단원에 걸쳐 설명하였는데, 본래의 작업 흐름에서 이벤트 구동식 브라우저의 작업 흐름으로 바뀌는 것을 다음과 같이 보여주었다.

- -
A comparison of the sequential and event-driven browser load sequences.
- -

 두 번째 그림에 보이는 처리방식은 마지막 단계의 작업흐름을 변화시킴으로써 첫 번째 그림의 단일 경로 처리흐름에서 반복순환 흐름으로 바뀐 것을 보여준다. 두 번째 그림은 Paint작업이 끝나면 새로운 이벤트 발생에 대한 처리(이벤트 핸들링)를 하기 위해 이벤트를 기다리게 된다. 이 혁신적인 개념을 이용하면 자원을 다 획득하지 않았더라도 페이지를 부분적으로 렌더링하는 것이 가능하며, 최초에는 자바스크립트에 의해 발전된 이벤트 구동에 의한 동작 효과적으로 구현할 수 있다. (이 강의는 여기를 포함한 다양한 경로로 볼 수 있다) 현재 모든 자바스크립트 코드 실행 환경에서는 이벤트와 이벤트 핸들링을 사용한다.

- -

이벤트 설계 패턴

- -

이벤트 시스템은 근본적으로는 단순한 프로그래밍 설계 패턴이다. 이 패턴는 기본적으로 이벤트의 종류와 다음 사항에 대해 합의된 약속을 기반으로 한다.

- -
    -
  • 각 이벤트를 가리키는 이벤트명 문자열
  • -
  • 각 이벤트의 핵심 프로퍼티를 나타내기 위한 자료구조의 형식
  • -
  • 각 이벤트를 발동할 자바스크립트 객체
  • -
- -

패턴을 구현하기 위해서는 다음이 필요하다.

- -
    -
  • 위에서 약속된 자료구조를 인수로 받는 자바스크립트 함수를 정의한다.
  • -
  • 이벤트를 발동할 객체에 약속된 해당 이벤트의 이벤트명을 사용하여 위의 함수를 등록한다.
  • -
- -

이 함수는 리스너(listener) 또는 핸들러(handler)라는 혼용된 명칭으로 불린다. 이 패턴은 커스텀 이벤트에 관한 글에서 설명한 대로의 완전한 커스텀 이벤트를 사용하여 쉽게 구현할 수 있다. 이 패턴은 사용자 입력, 브라우저 활동 등에 의해 발동되는 다양한 이벤트를 정의하는 최신 웹 브라우저에서도 많이 사용한다.

- -

 최신 웹 브라우저는 이 이벤트 패턴을 표준화된 방식으로 구현한다. 브라우저는 어떤 이벤트의 프로퍼티를 나타내는 자료 구조로서  EventPrototype 객체를 원천으로 하는 어떤 객체를 사용한다. 또한 이러한 자료구조를 핸들링할 함수에 대한 등록 메소드로서 addEventListener 메소드를 사용하는데 이것은 인수로서 이벤트명과 핸들러 함수를 받는다. 마지막으로 브라우저는 이벤트 발동자(emitter)로 수많은 객체를 정의하며 또한 이 객체들에 의해 생성되는 여러 이벤트형(event type)을 정의한다.

- -

버튼 이벤트 핸들러 데모

- -

하나의 예시로서 브라우저 button 요소(element)는 'click'이라는 이름의 이벤트를 마우스 클릭 또는 터치스크린의 경우 손가락 터치에 반응하여 발동시킨다. 버튼은 HTML 페이지에서 다음과 같이 정의할 수 있다.

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

그리고 자바스크립트 코드에서 'click' 이벤트에 대한 리스너로서의 함수, 즉 핸들러로 사용할 함수를 정의한다.

- -
var example_click_handler = function (ev){
-    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
-    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
-};
- -

그 다음 해당 Button 객체와 함께 위의 함수를 등록하는데, 첫 번째 방법은 HTML 페이지의 DOM(문서 객체 모델) 표현법을 이용하여 다음과 같이 스크립트상에서 나타내는 방법이다. 

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

또 다른 방법은 HTML 페이지 상에서 'onclick' 애트리뷰트의 값으로 핸들러로 쓸 함수를 대입시키는 것인데, 보통 이 방식은 매우 단순한 웹 페이지에서나 쓰인다.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement Javascript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

As a second example, much modern Javascript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

- -
var funcInit = function(){
-    // user code goes here and can safetly address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

- -

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: This list of will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- -

 

- -

The Event object hierarchy

- -

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - - -

 

- -

 

- -

 

diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index ab7c16ba17..1ea76dec68 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -106,7 +106,7 @@ /pt-BR/docs/DOM/Document.querySelector /pt-BR/docs/Web/API/Document/querySelector /pt-BR/docs/DOM/Document.querySelectorAll /pt-BR/docs/Web/API/Document/querySelectorAll /pt-BR/docs/DOM/Referencia_do_DOM /pt-BR/docs/Web/API/Document_Object_Model -/pt-BR/docs/DOM/Referencia_do_DOM/Events /pt-BR/docs/Web/API/Document_Object_Model/Events +/pt-BR/docs/DOM/Referencia_do_DOM/Events /pt-BR/docs/orphaned/Web/API/Document_Object_Model/Events /pt-BR/docs/DOM/Referencia_do_DOM/Examples /pt-BR/docs/Web/API/Document_Object_Model/Examples /pt-BR/docs/DOM/Referencia_do_DOM/How_to_create_a_DOM_tree /pt-BR/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree /pt-BR/docs/DOM/Referencia_do_DOM/Introdução /pt-BR/docs/Web/API/Document_Object_Model/Introduction @@ -561,6 +561,7 @@ /pt-BR/docs/Web/API/DocumentOrShadowRoot/activeElement /pt-BR/docs/Web/API/Document/activeElement /pt-BR/docs/Web/API/DocumentOrShadowRoot/elementFromPoint /pt-BR/docs/Web/API/Document/elementFromPoint /pt-BR/docs/Web/API/DocumentOrShadowRoot/getSelection /pt-BR/docs/Web/API/Document/getSelection +/pt-BR/docs/Web/API/Document_Object_Model/Events /pt-BR/docs/orphaned/Web/API/Document_Object_Model/Events /pt-BR/docs/Web/API/DocumentoXML /pt-BR/docs/Web/API/XMLDocument /pt-BR/docs/Web/API/Element.addEventListener /pt-BR/docs/Web/API/EventTarget/addEventListener /pt-BR/docs/Web/API/Element.getAttribute /pt-BR/docs/Web/API/Element/getAttribute @@ -730,8 +731,11 @@ /pt-BR/docs/Web/Guide/CSS/CSS_media_queries_(consultas_de_mídia_em_CSS) /pt-BR/docs/orphaned/Web/Guide/CSS/CSS_media_queries_(consultas_de_mídia_em_CSS) /pt-BR/docs/Web/Guide/CSS/Scaling_background_images /pt-BR/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images /pt-BR/docs/Web/Guide/CSS/Understanding_z_index /pt-BR/docs/Web/CSS/CSS_Positioning/Understanding_z_index +/pt-BR/docs/Web/Guide/Events /pt-BR/docs/orphaned/Web/Guide/Events /pt-BR/docs/Web/Guide/Events/Creating_and_triggering_events /pt-BR/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/pt-BR/docs/Web/Guide/Events/Event_handlers /pt-BR/docs/orphaned/Web/Guide/Events/Event_handlers /pt-BR/docs/Web/Guide/Events/Mutation_events /pt-BR/docs/orphaned/Web/Guide/Events/Mutation_events +/pt-BR/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /pt-BR/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /pt-BR/docs/Web/Guide/Events/Touch_events /pt-BR/docs/Web/API/Touch_events /pt-BR/docs/Web/Guide/Events/criando_e_disparando_eventos /pt-BR/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /pt-BR/docs/Web/Guide/Gráficos /pt-BR/docs/Web/Guide/Graphics diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index a7076ab9f3..248512bfde 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -5813,24 +5813,6 @@ "Sheppy" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:21:12.584Z", - "contributors": [ - "Sheppy" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-08-06T11:00:19.146Z", - "contributors": [ - "eziotristao" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2020-09-28T23:35:22.348Z", - "contributors": [ - "helton-mori-dev" - ] - }, "Web/Guide/Mobile": { "modified": "2020-04-05T18:24:36.523Z", "contributors": [ @@ -13208,12 +13190,6 @@ "meldenne" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2020-08-30T22:44:17.906Z", - "contributors": [ - "bermarques" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-03-23T22:11:58.983Z", "contributors": [ @@ -17367,5 +17343,29 @@ "contributors": [ "JefersonOliveira90" ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2020-08-30T22:44:17.906Z", + "contributors": [ + "bermarques" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-08-06T11:00:19.146Z", + "contributors": [ + "eziotristao" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:21:12.584Z", + "contributors": [ + "Sheppy" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2020-09-28T23:35:22.348Z", + "contributors": [ + "helton-mori-dev" + ] } } \ No newline at end of file diff --git a/files/pt-br/orphaned/web/api/document_object_model/events/index.html b/files/pt-br/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..76e6ec64e1 --- /dev/null +++ b/files/pt-br/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,83 @@ +--- +title: Events and the DOM +slug: orphaned/Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +
{{DefaultAPISidebar("DOM")}}
+ +

Introdução

+ +

Este capítulo descreve o Modelo de Eventos do DOM. A interface de Eventos é descrita, assim como a interface para registro de eventos em nodes(ou nódulos) no DOM, e event listeners, e vários outros exemplos que mostram como diversas interfaces de evento se relacionam uma com a outraThere is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Existe um excelente diagrama que explica claramente as três fases do percurso de eventos no DOM em DOM Level 3 Events draft.

+ +

Registrando event listeners

+ +

Existem 3 formas de registrar uma manipulação de eventos para um elemento DOM.

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', greet, false)
+function greet(event){
+    // print and have a look at the event object
+    // always print arguments in case of overlooking any other arguments
+    console.log('greet:', arguments)
+    alert('hello world')
+}
+
+ +

Este é o método que você deve usar em páginas web modernas.

+ +
+

Nota: Internet Explorer 6–8 não suportavam este método, oferecendo uma API {{domxref("EventTarget.attachEvent")}} parecida no lugar. Para compatibilidade cross-browser, use uma das muitas bibliotecas JavaScript disponíveis.

+
+ +

Mais detalhes podem encontrada na página de referência {{domxref("EventTarget.addEventListener")}}.

+ +

atributo HTML

+ +
<button onclick="alert('Hello world!')">
+
+ +

O código JavaScript no atributo é passado para o objeto Evento através do parâmetro event . O valor return é tratado de uma maneira especial, descrita na especificação HTML.

+ +
+

Cuidado: Este método deve ser evitado! Ele suja a marcação, e a faz menos legível. Preocupações com o conteúdo/estrutura e comportamento não são bem separadas, tornando mais díficil encontrar um bug.

+
+ +

DOM element properties

+ +
// Supondo que myButton seja um elemento button
+myButton.onclick = function(event){alert('Hello world')}
+
+ +

A função pode ser definida para receber um parâmetro event . O valor return é tratado de maneira especial, descrita na especificação HTML.

+ +

O problema deste método é que apenas uma manipulação pode ser definida por elemento e por evento.

+ +

Acessando interfaces doEvento

+ +

Manipulações do Evento podem ser atribuídas a vários objetos (incluindo elementos DOM, documentos, o {{domxref("window")}} object, etc.). Quando um evento ocorre, o objeto do evento é criado e passado sequencialmente ao event listeners.

+ +

A interface {{domxref("Event")}} é acessível de dentro da função manipuladora, atrás do objeto evento passado como primeiro argumento. O seguinte exemplo simples mostra como um objeto evento é passado á função manipuladora do evento, e pode usado de dentro de tal função.

+ +
function print(evt) {
+  // the evt parameter is automatically assigned the event object
+  // take care of the differences between console.log & alert
+  console.log('print:', evt)
+  alert(evt)
+}
+// any function should have an appropriate name, that's what called semantic
+table_el.onclick = print
+
+ + + + diff --git a/files/pt-br/orphaned/web/guide/events/event_handlers/index.html b/files/pt-br/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..34fdcb15f8 --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,165 @@ +--- +title: DOM onevent handlers +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

A plataforma web oferece várias maneiras de trabalhar com o DOM events. Duas abordagens comuns são: {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico onevent que dispara um evento. Este artigo se concentra em como o último funciona.

+ +

Registering onevent handlers

+ +

The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <body> element). Events are actions like:

+ +
    +
  • Being clicked
  • +
  • Detecting pressed keys
  • +
  • Getting focus
  • +
+ +

The on-event handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc.

+ +

You can specify an on<…> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:

+ +
    +
  • Adding an HTML {{Glossary("attribute")}} named on<eventtype>:
    + <button onclick="handleClick()">,
  • +
  • Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

An onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its {{domxref("EventTarget.addEventListener", "addEventListener()")}} method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} function.

+ +

When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. For example, given a button object myButton, you can do myButton.onclick(myEventObject) to call the event handler directly. If the event handler doesn't access any data form the event object, you can leave out the event when calling onclick().

+ +

This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.

+ +

Non-element objects

+ +

Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the progress event on instances of XMLHttpRequest:

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML onevent attributes

+ +

HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.

+ +

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

+ +

HTML

+ +

Given this HTML document:

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

+ +
let logElement = document.querySelector('div');
+let el = document.querySelector("a");
+
+function log(msg) { logElement.innerHTML += `${msg}<br>` };
+function anchorOnClick(event) { log("Changed onclick handler") };
+
+// Original Handler
+log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
+
+//Changing handler using .onclick
+log('<br>Changing onclick handler using <strong> onclick property </strong> ');
+
+el.onclick = anchorOnClick;
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
+
+//Changing handler using .setAttribute
+log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
+el.setAttribute("onclick", 'anchorOnClick(event)');
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
+ +

Result

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

+ +

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +
+

TBD (non-capturing listener)

+
+ +

Terminology

+ +

The term event handler may refer to:

+ +
    +
  • Any function or object that is registered to be notified of events
  • +
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • +
+ +

When discussing the various methods of listening to events:

+ +
    +
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • +
  • Event handler refers to a function registered via on… attributes or properties
  • +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ +

Detecting the presence of event handler properties

+ +

You can detect the presence of an event handler property with the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change Window.prototype.onload. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/pt-br/orphaned/web/guide/events/index.html b/files/pt-br/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..d705b4757c --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/index.html @@ -0,0 +1,37 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - TopicStub + - events +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

+

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

+ +

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+

The network requests made by a web page might trigger some events.

+

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+

Docs

+

{{LandingPageListSubpages}}

diff --git a/files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..950ddd0b4f --- /dev/null +++ b/files/pt-br/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,133 @@ +--- +title: Uma visão geral sobre Events e Handlers +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +
+

Este artigo apresenta uma visão geral sobre o design pattern usado para reagir a alterações que ocorrem quando o navegador acessa uma página, e dá um resumo sobre como os navegadores modernos reagem a eles.

+
+ +

Eventos e a manipulação de eventos fornecem uma técnica essencial em JavaScript para reagir a algum incidente quando o navegador acessa uma página, incluindo eventos de preparação para exibir a página, ou interação com algum conteúdo da página que estejam relacionados com o dispositivo onde o navagador está rodando, e muitas outras, como reprodução de áudio ou vídeo.

+ +

A manipulação de eventos tornou-se imprescindível com a evolução e mudança na arquitetura de renderização dos navegadores em relação a forma de busca e carregamento de informações na página. No início, os navegadores esperavam e recebiam os dados e recursos associados a página para analisar, processar e apresentar a página ao usuário. A página permanecia inalterada até uma requisição para um novo link. Atualmente, com a mudança para páginas dinâmicas, os navegadores estão sempre em um loop contínuo, processando, desenhando, apresentando conteúdo e esperando de algum novo evento. Os gatilhos (triggers) de evento podem ser a conclusão do carregamento de um arquivo na rede, por exemplo, uma imagem que agora pode ser mostrada na tela, a conclusão da análise de um recurso pelo navegador, o processamento do conteúdo HTML de uma página, a interação de um usuário com o conteúdo da página, com o clique em um botão. Douglas Crockford explica essa mudança de maneira eficaz em sua palestra, An Inconvenient API: The Theory of the DOM.

+ +

With the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. Event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which JavaScript leverages. (The talk is available from several sources, including this one.) Currently, all execution environments for JavaScript code use events and event handling.

+ +

The event design pattern

+ +

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

+ +
    +
  • the name String used for the event,
  • +
  • the type of the data structure used to represent the key properties of that event, and
  • +
  • the JavaScript object which will 'emit' that event.
  • +
+ +

The pattern is implemented by

+ +
    +
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • +
  • registering the function using the name String with the object which will emit the event.
  • +
+ +

The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using completely custom code, as explained in the article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

+ +

Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects.

+ +

Button Event Handler Demo

+ +

For example, browser button elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. We could define in the HTML page a button as:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

+ +
var example_click_handler = function (ev){
+    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
+    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
+};
+ +

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement JavaScript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

+ +

As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

+ +
var funcInit = function(){
+    // user code goes here and can safely address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+ +

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

+ +

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

+ +

Notable events

+ +

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

+ +

In general, we can distinguish events of different kinds based on the object emitting the event including:

+ +
    +
  • the window object, such as due to resizing the browser,
  • +
  • the window.screen object, such as due to changes in device orientation,
  • +
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • +
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • +
  • the XMLHttpRequest objects used for network requests, and
  • +
  • the media objects such as audio and video, when the media stream players change state.
  • +
+ +

although this list is currently incomplete.

+ +

Some notable events are:

+ +
+

Note: This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

+
+ +
    +
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • +
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • +
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • +
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • +
+ + + +

The Event object hierarchy

+ +

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

+ +

A partial diagram of the class hierarchy of event objects is:

+ +
+

Note: This diagram is incomplete.

+
+ +

+ +

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

+ +

Documents

+ +

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

+ + diff --git a/files/pt-br/web/api/document_object_model/events/index.html b/files/pt-br/web/api/document_object_model/events/index.html deleted file mode 100644 index cd82ef8b39..0000000000 --- a/files/pt-br/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Events and the DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events -original_slug: DOM/Referencia_do_DOM/Events ---- -
{{DefaultAPISidebar("DOM")}}
- -

Introdução

- -

Este capítulo descreve o Modelo de Eventos do DOM. A interface de Eventos é descrita, assim como a interface para registro de eventos em nodes(ou nódulos) no DOM, e event listeners, e vários outros exemplos que mostram como diversas interfaces de evento se relacionam uma com a outraThere is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

- -

Existe um excelente diagrama que explica claramente as três fases do percurso de eventos no DOM em DOM Level 3 Events draft.

- -

Registrando event listeners

- -

Existem 3 formas de registrar uma manipulação de eventos para um elemento DOM.

- -

{{domxref("EventTarget.addEventListener")}}

- -
// Assuming myButton is a button element
-myButton.addEventListener('click', greet, false)
-function greet(event){
-    // print and have a look at the event object
-    // always print arguments in case of overlooking any other arguments
-    console.log('greet:', arguments)
-    alert('hello world')
-}
-
- -

Este é o método que você deve usar em páginas web modernas.

- -
-

Nota: Internet Explorer 6–8 não suportavam este método, oferecendo uma API {{domxref("EventTarget.attachEvent")}} parecida no lugar. Para compatibilidade cross-browser, use uma das muitas bibliotecas JavaScript disponíveis.

-
- -

Mais detalhes podem encontrada na página de referência {{domxref("EventTarget.addEventListener")}}.

- -

atributo HTML

- -
<button onclick="alert('Hello world!')">
-
- -

O código JavaScript no atributo é passado para o objeto Evento através do parâmetro event . O valor return é tratado de uma maneira especial, descrita na especificação HTML.

- -
-

Cuidado: Este método deve ser evitado! Ele suja a marcação, e a faz menos legível. Preocupações com o conteúdo/estrutura e comportamento não são bem separadas, tornando mais díficil encontrar um bug.

-
- -

DOM element properties

- -
// Supondo que myButton seja um elemento button
-myButton.onclick = function(event){alert('Hello world')}
-
- -

A função pode ser definida para receber um parâmetro event . O valor return é tratado de maneira especial, descrita na especificação HTML.

- -

O problema deste método é que apenas uma manipulação pode ser definida por elemento e por evento.

- -

Acessando interfaces doEvento

- -

Manipulações do Evento podem ser atribuídas a vários objetos (incluindo elementos DOM, documentos, o {{domxref("window")}} object, etc.). Quando um evento ocorre, o objeto do evento é criado e passado sequencialmente ao event listeners.

- -

A interface {{domxref("Event")}} é acessível de dentro da função manipuladora, atrás do objeto evento passado como primeiro argumento. O seguinte exemplo simples mostra como um objeto evento é passado á função manipuladora do evento, e pode usado de dentro de tal função.

- -
function print(evt) {
-  // the evt parameter is automatically assigned the event object
-  // take care of the differences between console.log & alert
-  console.log('print:', evt)
-  alert(evt)
-}
-// any function should have an appropriate name, that's what called semantic
-table_el.onclick = print
-
- - - - diff --git a/files/pt-br/web/guide/events/event_handlers/index.html b/files/pt-br/web/guide/events/event_handlers/index.html deleted file mode 100644 index f558992d27..0000000000 --- a/files/pt-br/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: DOM onevent handlers -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers ---- -

A plataforma web oferece várias maneiras de trabalhar com o DOM events. Duas abordagens comuns são: {{domxref("EventTarget.addEventListener", "addEventListener()")}} e o específico onevent que dispara um evento. Este artigo se concentra em como o último funciona.

- -

Registering onevent handlers

- -

The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <body> element). Events are actions like:

- -
    -
  • Being clicked
  • -
  • Detecting pressed keys
  • -
  • Getting focus
  • -
- -

The on-event handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc.

- -

You can specify an on<…> event handler for a particular event (such as {{event("click")}}) for a given object in different ways:

- -
    -
  • Adding an HTML {{Glossary("attribute")}} named on<eventtype>:
    - <button onclick="handleClick()">,
  • -
  • Or by setting the corresponding {{Glossary("property/JavaScript", "property")}} from JavaScript:
    - document.querySelector("button").onclick = function(event) { … }.
  • -
- -

An onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its {{domxref("EventTarget.addEventListener", "addEventListener()")}} method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} function.

- -

When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. For example, given a button object myButton, you can do myButton.onclick(myEventObject) to call the event handler directly. If the event handler doesn't access any data form the event object, you can leave out the event when calling onclick().

- -

This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.

- -

Non-element objects

- -

Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the progress event on instances of XMLHttpRequest:

- -
const xhr = new XMLHttpRequest();
-xhr.onprogress = function() { … };
- -

HTML onevent attributes

- -

HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.

- -

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

- -

HTML

- -

Given this HTML document:

- -
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
-   <a onclick="log('Click!')">these three words</a>.
-</p>
-
-<div></div>
- -

JavaScript

- -

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

- -
let logElement = document.querySelector('div');
-let el = document.querySelector("a");
-
-function log(msg) { logElement.innerHTML += `${msg}<br>` };
-function anchorOnClick(event) { log("Changed onclick handler") };
-
-// Original Handler
-log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
-
-//Changing handler using .onclick
-log('<br>Changing onclick handler using <strong> onclick property </strong> ');
-
-el.onclick = anchorOnClick;
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
-
-//Changing handler using .setAttribute
-log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
-el.setAttribute("onclick", 'anchorOnClick(event)');
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
- -

Result

- -

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

- -

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.)

- -

Event handler's parameters, this binding, and the return value

- -

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

- -
    -
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • -
- -

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

- -

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification.

- -

When the event handler is invoked

- -
-

TBD (non-capturing listener)

-
- -

Terminology

- -

The term event handler may refer to:

- -
    -
  • Any function or object that is registered to be notified of events
  • -
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • -
- -

When discussing the various methods of listening to events:

- -
    -
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • -
  • Event handler refers to a function registered via on… attributes or properties
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

Browser compatibility

- -

Detecting the presence of event handler properties

- -

You can detect the presence of an event handler property with the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change Window.prototype.onload. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/pt-br/web/guide/events/index.html b/files/pt-br/web/guide/events/index.html deleted file mode 100644 index 65b5775a16..0000000000 --- a/files/pt-br/web/guide/events/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - TopicStub - - events -translation_of: Web/Guide/Events ---- -

{{draft()}}

-

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

-

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

-

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

-

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

-

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

-

The window in which the browser is displayed which might trigger events, for example, change size if the user maximizes the window or otherwise changes it.

-

The process loading of a web page might trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

-

The user interaction with the web page contents might trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction driven events include:

- -

The modification of the web page in structure or content might trigger some events, as is explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

-

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

-

The network requests made by a web page might trigger some events.

-

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

-
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
-

Docs

-

{{LandingPageListSubpages}}

diff --git a/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html b/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index 2593d5641e..0000000000 --- a/files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Uma visão geral sobre Events e Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

Este artigo apresenta uma visão geral sobre o design pattern usado para reagir a alterações que ocorrem quando o navegador acessa uma página, e dá um resumo sobre como os navegadores modernos reagem a eles.

-
- -

Eventos e a manipulação de eventos fornecem uma técnica essencial em JavaScript para reagir a algum incidente quando o navegador acessa uma página, incluindo eventos de preparação para exibir a página, ou interação com algum conteúdo da página que estejam relacionados com o dispositivo onde o navagador está rodando, e muitas outras, como reprodução de áudio ou vídeo.

- -

A manipulação de eventos tornou-se imprescindível com a evolução e mudança na arquitetura de renderização dos navegadores em relação a forma de busca e carregamento de informações na página. No início, os navegadores esperavam e recebiam os dados e recursos associados a página para analisar, processar e apresentar a página ao usuário. A página permanecia inalterada até uma requisição para um novo link. Atualmente, com a mudança para páginas dinâmicas, os navegadores estão sempre em um loop contínuo, processando, desenhando, apresentando conteúdo e esperando de algum novo evento. Os gatilhos (triggers) de evento podem ser a conclusão do carregamento de um arquivo na rede, por exemplo, uma imagem que agora pode ser mostrada na tela, a conclusão da análise de um recurso pelo navegador, o processamento do conteúdo HTML de uma página, a interação de um usuário com o conteúdo da página, com o clique em um botão. Douglas Crockford explica essa mudança de maneira eficaz em sua palestra, An Inconvenient API: The Theory of the DOM.

- -

With the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. Event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the HTML content of a page, the interaction of a user with the contents of the page e.g., clicks a button. Douglas Crockford explains this change effectively in several lectures, notably his talk, An Inconvenient API: The Theory of the DOM, which shows the change in flow from the original browser flow

- -
A comparison of the sequential and event-driven browser load sequences.
- -

to the event driven browser. The latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. The innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which JavaScript leverages. (The talk is available from several sources, including this one.) Currently, all execution environments for JavaScript code use events and event handling.

- -

The event design pattern

- -

The event system, at its core, is simply a programming design pattern. The pattern starts with an agreement over a kind of event and:

- -
    -
  • the name String used for the event,
  • -
  • the type of the data structure used to represent the key properties of that event, and
  • -
  • the JavaScript object which will 'emit' that event.
  • -
- -

The pattern is implemented by

- -
    -
  • defining a JavaScript function which takes as an argument the data structure which was agreed upon, and
  • -
  • registering the function using the name String with the object which will emit the event.
  • -
- -

The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using completely custom code, as explained in the article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity.

- -

Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called addEventListener which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects.

- -

Button Event Handler Demo

- -

For example, browser button elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap. We could define in the HTML page a button as:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

and, in our JavaScript code, we could first define a function to listen to that 'click' event:

- -
var example_click_handler = function (ev){
-    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
-    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
-};
- -

and second register our function with the the Button object, either on the scripting side using the DOM (Document Object Model) representation of the HTML page:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

or within the HTML page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivative MouseEvent object) and which will be fired by HTML button elements after user interaction. The code has no visible effect until a user interacts with the button either by placing the mouse pointer over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement JavaScript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred.

- -

As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as:

- -
var funcInit = function(){
-    // user code goes here and can safely address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
- -

so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.

- -

The pattern is therefore easy to learn and implement. The difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. There is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.

- -

Notable events

- -

Web browsers define a large number of events so it is not practical to list them all. The Event Reference attempts to maintain a list of the standard Events used in modern web browsers.

- -

In general, we can distinguish events of different kinds based on the object emitting the event including:

- -
    -
  • the window object, such as due to resizing the browser,
  • -
  • the window.screen object, such as due to changes in device orientation,
  • -
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • -
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • -
  • the XMLHttpRequest objects used for network requests, and
  • -
  • the media objects such as audio and video, when the media stream players change state.
  • -
- -

although this list is currently incomplete.

- -

Some notable events are:

- -
-

Note: This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question.

-
- -
    -
  • the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed,
  • -
  • the global object window emits an event called 'resize' when the height or the width of the browser window is changed by a user,
  • -
  • the DOM object document representing the HTML document emits an event called 'DOMContentLoaded' when the document has finished loading,
  • -
  • the DOM node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the DOM node in the HTML page.
  • -
- - - -

The Event object hierarchy

- -

The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object.

- -

A partial diagram of the class hierarchy of event objects is:

- -
-

Note: This diagram is incomplete.

-
- -

- -

The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object.

- -

Documents

- -

Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events:

- - diff --git a/files/pt-pt/_redirects.txt b/files/pt-pt/_redirects.txt index 5ae20c7836..60efdb4607 100644 --- a/files/pt-pt/_redirects.txt +++ b/files/pt-pt/_redirects.txt @@ -933,7 +933,8 @@ /pt-PT/docs/Web/Guide/AJAX/Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started /pt-PT/docs/Web/Guide/AJAX/Comunidade /pt-PT/docs/Web/Guide/AJAX/Community /pt-PT/docs/Web/Guide/CSS /pt-PT/docs/Learn/CSS -/pt-PT/docs/Web/Guide/Eventos /pt-PT/docs/Web/Guide/Events +/pt-PT/docs/Web/Guide/Eventos /pt-PT/docs/orphaned/Web/Guide/Events +/pt-PT/docs/Web/Guide/Events /pt-PT/docs/orphaned/Web/Guide/Events /pt-PT/docs/Web/Guide/Gráficos /pt-PT/docs/Web/Guide/Graphics /pt-PT/docs/Web/Guide/HTML /pt-PT/docs/Learn/HTML /pt-PT/docs/Web/Guide/HTML/Categorias_de_conteudo /pt-PT/docs/Web/Guide/HTML/Content_categories diff --git a/files/pt-pt/_wikihistory.json b/files/pt-pt/_wikihistory.json index 93134770ca..fdb997ca71 100644 --- a/files/pt-pt/_wikihistory.json +++ b/files/pt-pt/_wikihistory.json @@ -4423,12 +4423,6 @@ "Anonymous" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T22:01:48.833Z", - "contributors": [ - "Anonymous" - ] - }, "Web/Guide/Graphics": { "modified": "2019-03-18T21:46:51.581Z", "contributors": [ @@ -5188,5 +5182,11 @@ "contributors": [ "joaonunomota" ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T22:01:48.833Z", + "contributors": [ + "Anonymous" + ] } } \ No newline at end of file diff --git a/files/pt-pt/orphaned/web/guide/events/index.html b/files/pt-pt/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..f8f218d1c1 --- /dev/null +++ b/files/pt-pt/orphaned/web/guide/events/index.html @@ -0,0 +1,134 @@ +--- +title: Guia do programador de eventos +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Evento + - Guía + - Precisa de Atualização +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+ +

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+ +

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

Documentos

+ +

{{LandingPageListSubpages}}

+ +
+ + + + + +
diff --git a/files/pt-pt/web/guide/events/index.html b/files/pt-pt/web/guide/events/index.html deleted file mode 100644 index 88b9c2f2c8..0000000000 --- a/files/pt-pt/web/guide/events/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Guia do programador de eventos -slug: Web/Guide/Events -tags: - - DOM - - Evento - - Guía - - Precisa de Atualização -translation_of: Web/Guide/Events -original_slug: Web/Guide/Eventos ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Documentos

- -

{{LandingPageListSubpages}}

- -
- - - - - -
diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index 2e9994307f..f1cbdfc056 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -47,7 +47,7 @@ /ru/docs/Creating_Custom_Firefox_Extensions_with_the_Mozilla_Build_System /ru/docs/orphaned/Создание_расширения_для_Firefox_с_использованием_Mozilla_Build_System /ru/docs/DOM /ru/docs/conflicting/Web/API/Document_Object_Model /ru/docs/DOM/DOM_Reference /ru/docs/Web/API/Document_Object_Model -/ru/docs/DOM/DOM_Reference/Events /ru/docs/Web/API/Document_Object_Model/Events +/ru/docs/DOM/DOM_Reference/Events /ru/docs/orphaned/Web/API/Document_Object_Model/Events /ru/docs/DOM/DOM_Reference/Examples /ru/docs/Web/API/Document_Object_Model/Examples /ru/docs/DOM/DOM_Reference/Locating_DOM_elements_using_selectors /ru/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors /ru/docs/DOM/DOM_Reference/Введение /ru/docs/Web/API/Document_Object_Model/Introduction @@ -405,6 +405,7 @@ /ru/docs/Web/API/Document/domConfig /ru/docs/Web/API/Document /ru/docs/Web/API/DocumentOrShadowRoot/activeElement /ru/docs/Web/API/Document/activeElement /ru/docs/Web/API/DocumentOrShadowRoot/getSelection /ru/docs/Web/API/Document/getSelection +/ru/docs/Web/API/Document_Object_Model/Events /ru/docs/orphaned/Web/API/Document_Object_Model/Events /ru/docs/Web/API/Element.getBoundingClientRect /ru/docs/Web/API/Element/getBoundingClientRect /ru/docs/Web/API/Element.insertAdjacentHTML /ru/docs/Web/API/Element/insertAdjacentHTML /ru/docs/Web/API/Element/accessKey /ru/docs/Web/API/HTMLElement/accessKey @@ -600,8 +601,11 @@ /ru/docs/Web/Guide/CSS/Using_multi-column_layouts /ru/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts /ru/docs/Web/Guide/CSS/Visual_formatting_model /ru/docs/Web/CSS/Visual_formatting_model /ru/docs/Web/Guide/CSS/ispolzovanie_css_animatciy /ru/docs/Web/CSS/CSS_Animations/Using_CSS_animations +/ru/docs/Web/Guide/Events /ru/docs/orphaned/Web/Guide/Events /ru/docs/Web/Guide/Events/Creating_and_triggering_events /ru/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/ru/docs/Web/Guide/Events/Event_handlers /ru/docs/orphaned/Web/Guide/Events/Event_handlers /ru/docs/Web/Guide/Events/Media_events /ru/docs/orphaned/Web/Guide/Events/Media_events +/ru/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /ru/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /ru/docs/Web/Guide/Events/Создание_и_вызов_событий /ru/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events /ru/docs/Web/Guide/HTML /ru/docs/Learn/HTML /ru/docs/Web/Guide/HTML/Canvas_tutorial /ru/docs/Web/API/Canvas_API/Tutorial diff --git a/files/ru/_wikihistory.json b/files/ru/_wikihistory.json index a2df374b41..613d1d702f 100644 --- a/files/ru/_wikihistory.json +++ b/files/ru/_wikihistory.json @@ -11546,29 +11546,6 @@ "akhabibullina" ] }, - "Web/Guide/Events": { - "modified": "2020-08-20T10:40:53.452Z", - "contributors": [ - "bogpok", - "Llorephie", - "Tihoem", - "Jeremie" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-03-26T12:45:30.049Z", - "contributors": [ - "ellizii" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-06-24T11:18:00.027Z", - "contributors": [ - "kvandreev", - "MuradAz", - "curdwithraisins" - ] - }, "Web/Guide/HTML/Content_categories": { "modified": "2019-09-23T08:37:02.214Z", "contributors": [ @@ -19836,12 +19813,6 @@ "RAP1D" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-18T21:18:44.250Z", - "contributors": [ - "SphinxKnight" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-09-25T18:36:16.946Z", "contributors": [ @@ -25988,5 +25959,34 @@ "lazyexpert", "YuryT" ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-18T21:18:44.250Z", + "contributors": [ + "SphinxKnight" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-03-26T12:45:30.049Z", + "contributors": [ + "ellizii" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2020-08-20T10:40:53.452Z", + "contributors": [ + "bogpok", + "Llorephie", + "Tihoem", + "Jeremie" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-06-24T11:18:00.027Z", + "contributors": [ + "kvandreev", + "MuradAz", + "curdwithraisins" + ] } } \ No newline at end of file diff --git a/files/ru/orphaned/web/api/document_object_model/events/index.html b/files/ru/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..3bdc87fe96 --- /dev/null +++ b/files/ru/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,81 @@ +--- +title: Events and the DOM +slug: orphaned/Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Вступление

+ +

Вступление

+ +

В этой главе описывается модель событий DOM. Топ скрыть Интерфейс сам по себе описано, а также интерфейсы для регистрации событий на узлах в DOM, Также а обработчики события Главного , Также а Несколько больше Примеры, которые показывают, как Различные интерфейсы связаны друг события Главного с другом.

+ +

Существует отличная диаграмма, которая чётко объясняет события трёх этапов через DOM в проекте DOM Level 3 Events .

+ +

Также см. Пример 5: Распространение событий в главе «Примеры» для более подробного примера.

+ +

Регистрация обработчиков событий

+ +

Есть 3 способа регистрации обработанных событий для элемента DOM.

+ +

EventTarget.addEventListener

+ +
// Предполагая, что myButton является элементом кнопки
+myButton.addEventListener ('click', greet, false);
+function greet (event) {
+    // распечатать и посмотреть на объект события
+    // всегда печатать аргументы в случае пропуска любых других аргументов
+    console.log ('greet:', arguments);
+    оповещение («Привет, мир»);
+}
+
+ +

Это метод, который вы должны использовать на современных веб-страницах.

+ +

Примечание. Internet Explorer 6-8 не поддерживает этот метод, предлагая аналогичный {{domxref ("EventTarget.attachEvent")}} API. Для кросс-браузерной совместимости используйте одну из множества доступных библиотек JavaScript.

+ +

Дополнительную информацию можно найти на справочной странице {{domxref ("EventTarget.addEventListener")}}.

+ +

Атрибут HTML

+ +
<button onclick = "alert ('Hello world!')">
+
+ +

Код JavaScript в атрибуте передаётся объекту Event через eventпараметр. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

+ +

Этого пути следует избегать. Это делает разметку больше и менее читаемой. Проблемы содержания / структуры и поведения плохо разделены, что затрудняет поиск ошибки.

+ +

Свойства элемента DOM

+ +
// Предполагая, что myButton является элементом кнопки
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

Функция может быть определена для получения eventпараметра. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

+ +

Проблема этого метода в том, что для каждого элемента и для каждого события может быть установлен только один обработчик.

+ +

Доступ к интерфейсам событий

+ +

Обработчики событий могут быть присоединены к различным объектам, включая элементы DOM, документ, объект окна и т. Д. Когда происходит событие, объект события создаётся и последовательно передаётся обработчикам события.

+ +

Интерфейс {{domxref ("Event")}} доступен из функции-обработчика через объект события, переданный в качестве первого аргумента. В следующем простом примере показано, как объект события передаётся в функцию-обработчик события и может использоваться из одной такой функции.

+ +
function print(evt) {
+  // параметру evt автоматически назначается объект события
+  // позаботимся о различиях в console.log и alert
+  console.log('print:', evt);
+  alert(evt);
+}
+// любая функция должна иметь подходящее имя, это то, что называется семантическим
+table_el.onclick = print; 
+
+ + + + diff --git a/files/ru/orphaned/web/guide/events/event_handlers/index.html b/files/ru/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..c30df7b474 --- /dev/null +++ b/files/ru/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,167 @@ +--- +title: DOM onevent handlers +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

Веб-платформа предоставляет несколько способов получения уведомлений о событиях DOM. Два общих подхода - это {{domxref ("EventTarget.addEventListener", " addEventListener ()")}} и конкретные обработчики onevent . Эта страница посвящена тому, как работают последние.

+ +

Регистрация обработчиков onevent

+ +

Обработчики onevent - это свойства определённых элементов DOM, позволяющие управлять тем, как этот элемент реагирует на события. Элементы могут быть интерактивными (ссылки, кнопки, изображения, формы и т. д.) или неинтерактивными (например, элемент base <body>). События - это такие действия, как:

+ +
    +
  • Клик мышкой
  • +
  • Нажатие клавиш
  • +
  • Получение фокуса
  • +
+ +

Обработчик on-event обычно называется с именем события, на которое он реагирует, например onclick , onkeypress , onfocus и т. д.

+ +

Вы можете указать обработчик событий on<...> для конкретного события (например, {{event("click")}}) для данного объекта различными способами:

+ +
    +
  • Добавление HTML элемента {{Glossary("attribute")}} с событием on<eventtype>:
    + <button onclick="handleClick()">,
  • +
  • Или установив соответствующий параметр {{Glossary("property/JavaScript", "property")}} из JavaScript:
    + document.querySelector("button").onclick = function(event) { … }.
  • +
+ +

Свойство обработчика событий onevent  служит своего рода заполнителем, которому может быть назначен один обработчик событий. Чтобы разрешить установку нескольких обработчиков для одного и того же события на данном объекте, вы можете вызвать метод {{domxref("EventTarget.addEventListener", " addEventListener ()")}} , который управляет списком обработчиков для данного события на объекте. Затем обработчик можно удалить из объекта, вызвав его функцию {{domxref ("EventTarget.removeEventListener", "removeEventListener()")}} .

+ +

Когда происходит событие, которое применяется к элементу, каждый из его обработчиков событий вызывается, чтобы позволить им обрабатывать это событие один за другим. Вам не нужно вызывать их самостоятельно, хотя вы можете сделать это во многих случаях, чтобы легко имитировать происходящее событие. Например, учитывая объект кнопки myButton , вы можете сделать myButton.onclick(myEventObject) для прямого вызова обработчика событий. Если обработчик событий не имеет доступа к каким-либо данным из объекта event, вы можете пропустить это событие при вызове функции onclick() .

+ +

This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.

+ +

Это продолжается до тех пор, пока не будет вызван каждый обработчик, если только один из обработчиков событий явно не остановит обработку события, вызвав {{domxref("Event.stopPropagation", " stopPropagation ()")}} на самом объекте события.

+ +

Non-element objects

+ +

Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the progress event on instances of XMLHttpRequest:

+ +
const xhr = new XMLHttpRequest();
+xhr.onprogress = function() { … };
+ +

HTML onevent attributes

+ +

HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.

+ +

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

+ +

HTML

+ +

Given this HTML document:

+ +
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
+   <a onclick="log('Click!')">these three words</a>.
+</p>
+
+<div></div>
+ +

JavaScript

+ +

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

+ +
let logElement = document.querySelector('div');
+let el = document.querySelector("a");
+
+function log(msg) { logElement.innerHTML += `${msg}<br>` };
+function anchorOnClick(event) { log("Changed onclick handler") };
+
+// Original Handler
+log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
+
+//Changing handler using .onclick
+log('<br>Changing onclick handler using <strong> onclick property </strong> ');
+
+el.onclick = anchorOnClick;
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
+
+//Changing handler using .setAttribute
+log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
+el.setAttribute("onclick", 'anchorOnClick(event)');
+
+log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
+log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
+ +

Result

+ +

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.)

+ +

Event handler's parameters, this binding, and the return value

+ +

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

+ +
    +
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • +
+ +

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

+ +

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification.

+ +

When the event handler is invoked

+ +
+

TBD (non-capturing listener)

+
+ +

Terminology

+ +

The term event handler may refer to:

+ +
    +
  • Any function or object that is registered to be notified of events
  • +
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • +
+ +

When discussing the various methods of listening to events:

+ +
    +
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • +
  • Event handler refers to a function registered via on… attributes or properties
  • +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ +

Detecting the presence of event handler properties

+ +

You can detect the presence of an event handler property with the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change Window.prototype.onload. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/ru/orphaned/web/guide/events/index.html b/files/ru/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..955e0d2d21 --- /dev/null +++ b/files/ru/orphaned/web/guide/events/index.html @@ -0,0 +1,60 @@ +--- +title: Руководство разработчика событий +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

События связаны с:

+ +
    +
  • Шаблонами проектирования, использующимися для асинхронной обработки инцидентов, возникающих в жизненном цикле веб страницы
  • +
  • Именованием, характеризацией и использованием большого количества инцидентов различного типа
  • +
+ +

Статья Overview page содержит в краткой манере описание шаблонов проектирования и типов определяемых современными браузерами инцидентов

+ +
+ +

Custom events page описывает, как шаблон кода события может быть использован в пользовательском коде, чтобы определить новые типы событий, испускаемые от пользовательских объектов, зарегистрируйтесь функции слушателядля обработки этих событий, и вызова события в коде пользователя.

+ +

Остальные страницы описывают, как использовать события разных видов, определённых в веб-браузерах. К сожалению, эти события были определены по частям, веб-браузеры развивались таким образом, что нет удовлетворения систематическим характеристикам событий встроенным или определённым в современных веб-браузерах.

+ +

Устройство, на котором работа веб-браузера может спровоцировать событие, например связанное с изменением его положения и ориентации в реальном мире, частично описано page on orientation coordinate systems и page on the use of 3D transforms. Они разные, но похожи, с изменённой вертикальной ориентации устройства.

+ +

Окно в котором отображается браузер может вызвать события, к примеру, изменить размер, если пользователь максимизирует окно или изменит его размер.

+ +

Процесс загрузки веб-страницы может вызвать ответное событие на завершение различных этапов загрузки, анализирования и перевода веб-страниц отображаемых пользователю.

+ +

Взаимодействие пользователя с содержимым веб-страницы может вызвать события. События, вызванные взаимодействием пользователя развивались в первые годы проектирования браузера, и включают в себя сложную систему, определяющую последовательность, в которой будет вызываться событие и манера, в которой эта последовательность может быть контролируемой. Различные типы взаимодействия пользователя с управляемыми событиями:

+ + + +

Модификация в структуре веб-страницы или содержании может быть вызвано некоторым событием описанным в mutation events page, но их использование устарело в пользу более лёгкого Mutation Observer подхода.

+ +

Потоки Медиа, встроенный в HTML документа, может вызвать некоторые события, страница описания media events.

+ +

Сетевые запросы, сделанные веб-страницей, могут вызвать некоторые события.

+ +

Есть много других источников событий, определённых в веб-браузере, страницы которых пока не доступны в данном руководстве.

+ +
+

Примечание: Это руководство событие Разработчика нуждается в существенной работе.Структура должна быть реорганизована и страницы переписаны. Мы надеемся, что все, что вы знаете и должны знать о событиях будет опубликовано здесь.

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/ru/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/ru/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..ea9b25b46d --- /dev/null +++ b/files/ru/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,131 @@ +--- +title: Обзор событий и обработчиков +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +
+

Эта обзорная статья о событиях и их обработчиках описывает шаблон проектирования кода, который используется для реагирования на события, возникающие, когда браузер получает доступ к web-странице, и содержит подборку типов подобных событий, которые современные браузеры могут обрабатывать.

+
+ +

События и их обработчики представляют собой основную технику в JavaScript для реагирования на события, возникающие, когда браузер получает доступ к web-странице, включая события о подготовке страницы к отображению, взаимодействии с её содержимым, в зависимости от устройства, на котором браузер был запущен, и многие другие случаи, такие как воспроизведение потоковой медиа-информации или расчёт времени анимации.

+ +

События и обработчики событий заняли центральное место в web-программировании с добавлением языка в браузеры, сопровождая смену архитектуры рендеринга от перехвата и загрузки страницы к управлению с помощью событий, основанном на перекомпоновке (reflow). Сначала браузер ожидает, пока он получит все ресурсы, связанные со страницей, чтобы проанализировать, обработать, отрисовать и предоставить страницу пользователю. Отрисованная страница остаётся неизменной, пока браузер не запросит новую. С изменением в подходе к рендерингу динамической страницы, браузер непрерывно зацикливается между обработкой, отрисовкой, представлением содержимого и ожиданием некоторого нового триггера события. Триггеры событий включают, например, завершение загрузки ресурса по сети, скачивание изображений, которые теперь могут быть отрисованы на экране, завершение браузером анализа ресурса, обработку HTML-содержимого страницы, взаимодействие пользователя с содержимым страницы, нажатия кнопок. Дуглас Крокфорд хорошо объясняет это изменение в нескольких лекциях, особенно своей речи "Неудобные API: Теория DOM", которая описывает изменения в потоке изначального потока браузера от управляемого событиями браузера.

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

Второй подход изменяет последние шаги, переходя от простого потока к бесконечному циклу, где ожидание и обработка возникновения новых событий следует за отрисовкой. Введение динамического подхода позволяет странице быть частично отрендериной, даже когда браузер ещё не закончил извлечение всех ресурсов; это так же разрешено для действий, управляемыми событиями, которые JavaScript использует. (Речь доступна на нескольких ресурсах, включая этот.) На данный момент, все среды исполнения JavaScript используют события и их обработчики.

+ +

Шаблон проектирования событий

+ +

Система событий, по своей сути, простой программный шаблон проектирования. Он начинается с соглашения о виде события и:

+ +
    +
  • имени-строки, используемой для события,
  • +
  • типа структуры данных, используемых для представления ключевых свойств события,
  • +
  • объекта JavaScript, который будет 'вызывать' это событие.
  • +
+ +

Шаблон реализуется с помощью:

+ +
    +
  • определение JavaScript-функции, которая принимает в качестве аргумента структуру данных, которая была согласована ранее, и
  • +
  • регистрации функции с помощью имени-строки через объект, который будет вызывать событие.
  • +
+ +

Функция считается "обработчиком", где оба именами взаимозаменяемы. Этому шаблону можно легко следовать с использованием полностью пользовательского кода, как объяснено в статье о пользовательских событиях. Шаблон так же используется современными web-браузерами, определяющими множество событий, которые вызываются в ответ на пользовательский ввод или активность браузера.

+ +

Современные браузеры следуют событийному шаблону, используя стандартизированный подход. В качестве структуры данных для свойств события они применяют объект, полученный от объекта EventPrototype. Для регистратрации функции, которая будет обрабатывать эту структуру данных, используется метод, называемый addEventListener, который ожидает в качестве аргумента имя-строку, соответствующую типу события, и функцию-обработчика. В итоге, браузеры определяют огромное число объектов источников событий и широкое разнообразие типов событий, сформированных объектами.

+ +

Пример обработчика события кнопки

+ +

К примеру, браузерный элемент button предназначен для вызова события с именем  'click' в ответ на нажатие кнопки мыши или прикосновение пальца к чувствительной части экрана. В HTML мы можем определить  button как:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

и, в коде JavaScript, мы можем сначала определить функцию для обработки этого события 'click' :

+ +
var example_click_handler = function (ev){
+    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
+    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
+};
+ +

и затем зарегистрировать свою функцию с помощью объекта Button или со стороны скрипта, используя представление DOM (Document Object Model) на HTML-странице:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

или на самой HTML-странице, добавив функцию как значение атрибута 'onclick', хотя этот вариант обычно используется на очень  простых web-страницах.

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

Этот код полагается на соглашение о том, что существует некоторый вид события, называемый 'click' , который вызовет все функции-обработчики (или 'обработчик') с объектом-аргументом Event (на данный момент, в этом случае производный от объекта MouseEvent ) и будет запущен после манипуляций пользователя с элементами button на HTML-странице. Код не имеет видимого воздействия, пока пользователь не использует кнопки, наводит указатель мыши на элемент HTML и нажимает на левую кнопку или устанавливает палец или стилус на некоторое место на экране, выше кнопки; когда это произойдёт, buttonDOMElement объекта JavaScript вызовет функцию example_click_handler с объектом Event в качестве аргумента. Функция, в свою очередь, исполнит любые действия, описанные программистом, в данном случае отрыв диалоговое окно HTML. Заметим, что обработчик имеет доступ к объекту ev, так как тот передаётся в качестве аргумента; объект содержит информацию о событие, в частности время его возникновения.

+ +

Во втором варианте, интегрирован в web-страницу намного более современный JavaScript обёрнут в событийный вызов функции, чтобы убедиться, что код будет выполнен только тогда, когда HTML будет обработан и доступен для изменения или декорирования. Например, код может быть объявлен так:

+ +
var funcInit = function(){
+    // user code goes here and can safely address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+ +

так что этот код будет вызван только после того, как объект document вызовет событие 'DOMContentLoaded', потому что HTML был проанализирован и были созданы объекты Javasript,   представляющие каждый узел HTML-документа. Заметим, что в этом примере, код даже не передаёт аргумент события в функцию, потому что тому никогда не понадобится использовать данные, описанные в нем; скорее, код всего лишь нужно подождать, пока не случится событие.

+ +

Шаблон легко изучить и внедрить. Сложность с событиями возникает из-за необходимости изучить большое разнообразие событий, которые представлены в современных web-браузерах. Так же есть некоторая сложность в понимании, как писать обработчики, так как данный код работает асинхронно и потенциально может быть вызван несколько раз подряд, но в немного другой ситуации.

+ +

Важные события

+ +

Web-браузеры определяют большое число событий, поэтому не практично описывать их все. Event Reference призван содержать список стандартных событий, используемых в современных браузерах.

+ +

В общем случае, события различного вида выделяют, основываясь на объекте, который вызывает данное событие, включая:

+ +
    +
  • объект window, на случай изменения размера браузера,
  • +
  • объект window.screen, на случай изменения положения устройства,
  • +
  • объект document, включая загрузку, модификацию, пользовательское взаимодействие и разгрузку страницы,
  • +
  • объект в DOM (объектная модель документа) дереве, включая пользовательское взаимодействие или изменения,
  • +
  • объект XMLHttpRequest, используемый для запросов сети, и
  • +
  • медиа-объекты, такие как audio и video, когда медиа-потоковые плееры изменяют состояние.
  • +
+ +

хотя этот список на данный момент неполный.

+ +

Некоторые события, которые стоит отметить:

+ +
+

Примечание: Этот список событий будет нуждаться в доработке, чтобы соответствовать действительности; эта работа ожидает некоторой глобальной реорганизации в документе. Так же нужно найти хорошее объяснение событий, включая события во время загрузки страницы, таких, как частично описанных в этой статье  или  этом вопросе на  Stack Overflow.

+
+ +
    +
  • глобальный объект window вызывает событие, называемое 'load', когда страница закончила рендеринг, подразумевая, что все ресурсы были скачаны и применены, так что скрипт был выполнен и изображения отображены,
  • +
  • глобальный объект window вызывает событие, называемое 'resize', когда высота или ширина окна браузера была изменена пользователем,
  • +
  • объект DOM document, представляющий HTML-документ, вызывает событие, называемое 'DOMContentLoaded', когда документ закончил загрузку,
  • +
  • объект узла DOM, такой как div или button, вызывающий событие, называемое 'click', когда пользователь нажимает кнопку мыши, пока её указатель находится поверх узла DOM на HTML-странице.
  • +
+ + + +

Иерархия объекта событий

+ +

Web-браузер определяет множество событий различного вида. Каждое описание включает, как структуру данных, передающуюся в обработчика, объект, который наследуется от объекта EventPrototype.

+ +

Частичная диаграмма иерархии класса объекта событий:

+ +
+

Примечание: Эта диаграмма неполная.

+
+ +

+ +

Web API Документация содержит страницу, описывающую объект событий, который так же включает известные события DOM, подклассы объекта Event.

+ +

Документации

+ +

Три ресурса на MDN (Mozilla Developer Network) частично полезные для программистов, желающих работать с событиями:

+ + diff --git a/files/ru/web/api/document_object_model/events/index.html b/files/ru/web/api/document_object_model/events/index.html deleted file mode 100644 index baf74bbb29..0000000000 --- a/files/ru/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Events and the DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events -original_slug: DOM/DOM_Reference/Events ---- -

Вступление

- -

Вступление

- -

В этой главе описывается модель событий DOM. Топ скрыть Интерфейс сам по себе описано, а также интерфейсы для регистрации событий на узлах в DOM, Также а обработчики события Главного , Также а Несколько больше Примеры, которые показывают, как Различные интерфейсы связаны друг события Главного с другом.

- -

Существует отличная диаграмма, которая чётко объясняет события трёх этапов через DOM в проекте DOM Level 3 Events .

- -

Также см. Пример 5: Распространение событий в главе «Примеры» для более подробного примера.

- -

Регистрация обработчиков событий

- -

Есть 3 способа регистрации обработанных событий для элемента DOM.

- -

EventTarget.addEventListener

- -
// Предполагая, что myButton является элементом кнопки
-myButton.addEventListener ('click', greet, false);
-function greet (event) {
-    // распечатать и посмотреть на объект события
-    // всегда печатать аргументы в случае пропуска любых других аргументов
-    console.log ('greet:', arguments);
-    оповещение («Привет, мир»);
-}
-
- -

Это метод, который вы должны использовать на современных веб-страницах.

- -

Примечание. Internet Explorer 6-8 не поддерживает этот метод, предлагая аналогичный {{domxref ("EventTarget.attachEvent")}} API. Для кросс-браузерной совместимости используйте одну из множества доступных библиотек JavaScript.

- -

Дополнительную информацию можно найти на справочной странице {{domxref ("EventTarget.addEventListener")}}.

- -

Атрибут HTML

- -
<button onclick = "alert ('Hello world!')">
-
- -

Код JavaScript в атрибуте передаётся объекту Event через eventпараметр. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

- -

Этого пути следует избегать. Это делает разметку больше и менее читаемой. Проблемы содержания / структуры и поведения плохо разделены, что затрудняет поиск ошибки.

- -

Свойства элемента DOM

- -
// Предполагая, что myButton является элементом кнопки
-myButton.onclick = function(event){alert('Hello world');};
-
- -

Функция может быть определена для получения eventпараметра. Возвращаемое значение обрабатывается особым образом, описанным в спецификации HTML .

- -

Проблема этого метода в том, что для каждого элемента и для каждого события может быть установлен только один обработчик.

- -

Доступ к интерфейсам событий

- -

Обработчики событий могут быть присоединены к различным объектам, включая элементы DOM, документ, объект окна и т. Д. Когда происходит событие, объект события создаётся и последовательно передаётся обработчикам события.

- -

Интерфейс {{domxref ("Event")}} доступен из функции-обработчика через объект события, переданный в качестве первого аргумента. В следующем простом примере показано, как объект события передаётся в функцию-обработчик события и может использоваться из одной такой функции.

- -
function print(evt) {
-  // параметру evt автоматически назначается объект события
-  // позаботимся о различиях в console.log и alert
-  console.log('print:', evt);
-  alert(evt);
-}
-// любая функция должна иметь подходящее имя, это то, что называется семантическим
-table_el.onclick = print; 
-
- - - - diff --git a/files/ru/web/guide/events/event_handlers/index.html b/files/ru/web/guide/events/event_handlers/index.html deleted file mode 100644 index fbbdde6848..0000000000 --- a/files/ru/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: DOM onevent handlers -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers ---- -

Веб-платформа предоставляет несколько способов получения уведомлений о событиях DOM. Два общих подхода - это {{domxref ("EventTarget.addEventListener", " addEventListener ()")}} и конкретные обработчики onevent . Эта страница посвящена тому, как работают последние.

- -

Регистрация обработчиков onevent

- -

Обработчики onevent - это свойства определённых элементов DOM, позволяющие управлять тем, как этот элемент реагирует на события. Элементы могут быть интерактивными (ссылки, кнопки, изображения, формы и т. д.) или неинтерактивными (например, элемент base <body>). События - это такие действия, как:

- -
    -
  • Клик мышкой
  • -
  • Нажатие клавиш
  • -
  • Получение фокуса
  • -
- -

Обработчик on-event обычно называется с именем события, на которое он реагирует, например onclick , onkeypress , onfocus и т. д.

- -

Вы можете указать обработчик событий on<...> для конкретного события (например, {{event("click")}}) для данного объекта различными способами:

- -
    -
  • Добавление HTML элемента {{Glossary("attribute")}} с событием on<eventtype>:
    - <button onclick="handleClick()">,
  • -
  • Или установив соответствующий параметр {{Glossary("property/JavaScript", "property")}} из JavaScript:
    - document.querySelector("button").onclick = function(event) { … }.
  • -
- -

Свойство обработчика событий onevent  служит своего рода заполнителем, которому может быть назначен один обработчик событий. Чтобы разрешить установку нескольких обработчиков для одного и того же события на данном объекте, вы можете вызвать метод {{domxref("EventTarget.addEventListener", " addEventListener ()")}} , который управляет списком обработчиков для данного события на объекте. Затем обработчик можно удалить из объекта, вызвав его функцию {{domxref ("EventTarget.removeEventListener", "removeEventListener()")}} .

- -

Когда происходит событие, которое применяется к элементу, каждый из его обработчиков событий вызывается, чтобы позволить им обрабатывать это событие один за другим. Вам не нужно вызывать их самостоятельно, хотя вы можете сделать это во многих случаях, чтобы легко имитировать происходящее событие. Например, учитывая объект кнопки myButton , вы можете сделать myButton.onclick(myEventObject) для прямого вызова обработчика событий. Если обработчик событий не имеет доступа к каким-либо данным из объекта event, вы можете пропустить это событие при вызове функции onclick() .

- -

This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling {{domxref("Event.stopPropagation", "stopPropagation()")}} on the event object itself.

- -

Это продолжается до тех пор, пока не будет вызван каждый обработчик, если только один из обработчиков событий явно не остановит обработку события, вызвав {{domxref("Event.stopPropagation", " stopPropagation ()")}} на самом объекте события.

- -

Non-element objects

- -

Event handlers can also be set with properties on non-element objects that generate events, like {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others. For example, for the progress event on instances of XMLHttpRequest:

- -
const xhr = new XMLHttpRequest();
-xhr.onprogress = function() { … };
- -

HTML onevent attributes

- -

HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML.

- -

Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.

- -

HTML

- -

Given this HTML document:

- -
<p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on
-   <a onclick="log('Click!')">these three words</a>.
-</p>
-
-<div></div>
- -

JavaScript

- -

Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object's property.

- -
let logElement = document.querySelector('div');
-let el = document.querySelector("a");
-
-function log(msg) { logElement.innerHTML += `${msg}<br>` };
-function anchorOnClick(event) { log("Changed onclick handler") };
-
-// Original Handler
-log(`Element's onclick as a JavaScript property: <code> ${el.onclick.toString()} </code>`);
-
-//Changing handler using .onclick
-log('<br>Changing onclick handler using <strong> onclick property </strong> ');
-
-el.onclick = anchorOnClick;
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`But the HTML attribute is unchanged: <code> ${el.getAttribute("onclick")} </code><br>`);
-
-//Changing handler using .setAttribute
-log('<hr/><br> Changing onclick handler using <strong> setAttribute method </strong> ');
-el.setAttribute("onclick", 'anchorOnClick(event)');
-
-log(`Changed the property to: <code> ${el.onclick.toString()} </code>`);
-log(`Now even the HTML attribute has changed: <code> ${el.getAttribute("onclick")} </code><br>`);
- -

Result

- -

{{ EmbedLiveSample('HTML_onevent_attributes', '', '', '', 'Web/Guide/Events/Event_handlers') }}

- -

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements instead set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.)

- -

Event handler's parameters, this binding, and the return value

- -

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

- -
    -
  • event — for all event handlers except {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • event, source, lineno, colno, and error for the {{domxref("GlobalEventHandlers.onerror", "onerror")}} event handler. Note that the event parameter actually contains the error message as a string.
  • -
- -

When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.

- -

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algorithm" in the HTML specification.

- -

When the event handler is invoked

- -
-

TBD (non-capturing listener)

-
- -

Terminology

- -

The term event handler may refer to:

- -
    -
  • Any function or object that is registered to be notified of events
  • -
  • Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { … }.
  • -
- -

When discussing the various methods of listening to events:

- -
    -
  • Event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}}
  • -
  • Event handler refers to a function registered via on… attributes or properties
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

Browser compatibility

- -

Detecting the presence of event handler properties

- -

You can detect the presence of an event handler property with the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

You can't set or access the values of any IDL-defined attributes on DOM prototype objects. That means you can't, for example, change Window.prototype.onload. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/ru/web/guide/events/index.html b/files/ru/web/guide/events/index.html deleted file mode 100644 index cd85e3eeac..0000000000 --- a/files/ru/web/guide/events/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Руководство разработчика событий -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

События связаны с:

- -
    -
  • Шаблонами проектирования, использующимися для асинхронной обработки инцидентов, возникающих в жизненном цикле веб страницы
  • -
  • Именованием, характеризацией и использованием большого количества инцидентов различного типа
  • -
- -

Статья Overview page содержит в краткой манере описание шаблонов проектирования и типов определяемых современными браузерами инцидентов

- -
- -

Custom events page описывает, как шаблон кода события может быть использован в пользовательском коде, чтобы определить новые типы событий, испускаемые от пользовательских объектов, зарегистрируйтесь функции слушателядля обработки этих событий, и вызова события в коде пользователя.

- -

Остальные страницы описывают, как использовать события разных видов, определённых в веб-браузерах. К сожалению, эти события были определены по частям, веб-браузеры развивались таким образом, что нет удовлетворения систематическим характеристикам событий встроенным или определённым в современных веб-браузерах.

- -

Устройство, на котором работа веб-браузера может спровоцировать событие, например связанное с изменением его положения и ориентации в реальном мире, частично описано page on orientation coordinate systems и page on the use of 3D transforms. Они разные, но похожи, с изменённой вертикальной ориентации устройства.

- -

Окно в котором отображается браузер может вызвать события, к примеру, изменить размер, если пользователь максимизирует окно или изменит его размер.

- -

Процесс загрузки веб-страницы может вызвать ответное событие на завершение различных этапов загрузки, анализирования и перевода веб-страниц отображаемых пользователю.

- -

Взаимодействие пользователя с содержимым веб-страницы может вызвать события. События, вызванные взаимодействием пользователя развивались в первые годы проектирования браузера, и включают в себя сложную систему, определяющую последовательность, в которой будет вызываться событие и манера, в которой эта последовательность может быть контролируемой. Различные типы взаимодействия пользователя с управляемыми событиями:

- - - -

Модификация в структуре веб-страницы или содержании может быть вызвано некоторым событием описанным в mutation events page, но их использование устарело в пользу более лёгкого Mutation Observer подхода.

- -

Потоки Медиа, встроенный в HTML документа, может вызвать некоторые события, страница описания media events.

- -

Сетевые запросы, сделанные веб-страницей, могут вызвать некоторые события.

- -

Есть много других источников событий, определённых в веб-браузере, страницы которых пока не доступны в данном руководстве.

- -
-

Примечание: Это руководство событие Разработчика нуждается в существенной работе.Структура должна быть реорганизована и страницы переписаны. Мы надеемся, что все, что вы знаете и должны знать о событиях будет опубликовано здесь.

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/ru/web/guide/events/overview_of_events_and_handlers/index.html b/files/ru/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index cd267fea47..0000000000 --- a/files/ru/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Обзор событий и обработчиков -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

Эта обзорная статья о событиях и их обработчиках описывает шаблон проектирования кода, который используется для реагирования на события, возникающие, когда браузер получает доступ к web-странице, и содержит подборку типов подобных событий, которые современные браузеры могут обрабатывать.

-
- -

События и их обработчики представляют собой основную технику в JavaScript для реагирования на события, возникающие, когда браузер получает доступ к web-странице, включая события о подготовке страницы к отображению, взаимодействии с её содержимым, в зависимости от устройства, на котором браузер был запущен, и многие другие случаи, такие как воспроизведение потоковой медиа-информации или расчёт времени анимации.

- -

События и обработчики событий заняли центральное место в web-программировании с добавлением языка в браузеры, сопровождая смену архитектуры рендеринга от перехвата и загрузки страницы к управлению с помощью событий, основанном на перекомпоновке (reflow). Сначала браузер ожидает, пока он получит все ресурсы, связанные со страницей, чтобы проанализировать, обработать, отрисовать и предоставить страницу пользователю. Отрисованная страница остаётся неизменной, пока браузер не запросит новую. С изменением в подходе к рендерингу динамической страницы, браузер непрерывно зацикливается между обработкой, отрисовкой, представлением содержимого и ожиданием некоторого нового триггера события. Триггеры событий включают, например, завершение загрузки ресурса по сети, скачивание изображений, которые теперь могут быть отрисованы на экране, завершение браузером анализа ресурса, обработку HTML-содержимого страницы, взаимодействие пользователя с содержимым страницы, нажатия кнопок. Дуглас Крокфорд хорошо объясняет это изменение в нескольких лекциях, особенно своей речи "Неудобные API: Теория DOM", которая описывает изменения в потоке изначального потока браузера от управляемого событиями браузера.

- -
A comparison of the sequential and event-driven browser load sequences.
- -

Второй подход изменяет последние шаги, переходя от простого потока к бесконечному циклу, где ожидание и обработка возникновения новых событий следует за отрисовкой. Введение динамического подхода позволяет странице быть частично отрендериной, даже когда браузер ещё не закончил извлечение всех ресурсов; это так же разрешено для действий, управляемыми событиями, которые JavaScript использует. (Речь доступна на нескольких ресурсах, включая этот.) На данный момент, все среды исполнения JavaScript используют события и их обработчики.

- -

Шаблон проектирования событий

- -

Система событий, по своей сути, простой программный шаблон проектирования. Он начинается с соглашения о виде события и:

- -
    -
  • имени-строки, используемой для события,
  • -
  • типа структуры данных, используемых для представления ключевых свойств события,
  • -
  • объекта JavaScript, который будет 'вызывать' это событие.
  • -
- -

Шаблон реализуется с помощью:

- -
    -
  • определение JavaScript-функции, которая принимает в качестве аргумента структуру данных, которая была согласована ранее, и
  • -
  • регистрации функции с помощью имени-строки через объект, который будет вызывать событие.
  • -
- -

Функция считается "обработчиком", где оба именами взаимозаменяемы. Этому шаблону можно легко следовать с использованием полностью пользовательского кода, как объяснено в статье о пользовательских событиях. Шаблон так же используется современными web-браузерами, определяющими множество событий, которые вызываются в ответ на пользовательский ввод или активность браузера.

- -

Современные браузеры следуют событийному шаблону, используя стандартизированный подход. В качестве структуры данных для свойств события они применяют объект, полученный от объекта EventPrototype. Для регистратрации функции, которая будет обрабатывать эту структуру данных, используется метод, называемый addEventListener, который ожидает в качестве аргумента имя-строку, соответствующую типу события, и функцию-обработчика. В итоге, браузеры определяют огромное число объектов источников событий и широкое разнообразие типов событий, сформированных объектами.

- -

Пример обработчика события кнопки

- -

К примеру, браузерный элемент button предназначен для вызова события с именем  'click' в ответ на нажатие кнопки мыши или прикосновение пальца к чувствительной части экрана. В HTML мы можем определить  button как:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

и, в коде JavaScript, мы можем сначала определить функцию для обработки этого события 'click' :

- -
var example_click_handler = function (ev){
-    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
-    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
-};
- -

и затем зарегистрировать свою функцию с помощью объекта Button или со стороны скрипта, используя представление DOM (Document Object Model) на HTML-странице:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

или на самой HTML-странице, добавив функцию как значение атрибута 'onclick', хотя этот вариант обычно используется на очень  простых web-страницах.

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

Этот код полагается на соглашение о том, что существует некоторый вид события, называемый 'click' , который вызовет все функции-обработчики (или 'обработчик') с объектом-аргументом Event (на данный момент, в этом случае производный от объекта MouseEvent ) и будет запущен после манипуляций пользователя с элементами button на HTML-странице. Код не имеет видимого воздействия, пока пользователь не использует кнопки, наводит указатель мыши на элемент HTML и нажимает на левую кнопку или устанавливает палец или стилус на некоторое место на экране, выше кнопки; когда это произойдёт, buttonDOMElement объекта JavaScript вызовет функцию example_click_handler с объектом Event в качестве аргумента. Функция, в свою очередь, исполнит любые действия, описанные программистом, в данном случае отрыв диалоговое окно HTML. Заметим, что обработчик имеет доступ к объекту ev, так как тот передаётся в качестве аргумента; объект содержит информацию о событие, в частности время его возникновения.

- -

Во втором варианте, интегрирован в web-страницу намного более современный JavaScript обёрнут в событийный вызов функции, чтобы убедиться, что код будет выполнен только тогда, когда HTML будет обработан и доступен для изменения или декорирования. Например, код может быть объявлен так:

- -
var funcInit = function(){
-    // user code goes here and can safely address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
- -

так что этот код будет вызван только после того, как объект document вызовет событие 'DOMContentLoaded', потому что HTML был проанализирован и были созданы объекты Javasript,   представляющие каждый узел HTML-документа. Заметим, что в этом примере, код даже не передаёт аргумент события в функцию, потому что тому никогда не понадобится использовать данные, описанные в нем; скорее, код всего лишь нужно подождать, пока не случится событие.

- -

Шаблон легко изучить и внедрить. Сложность с событиями возникает из-за необходимости изучить большое разнообразие событий, которые представлены в современных web-браузерах. Так же есть некоторая сложность в понимании, как писать обработчики, так как данный код работает асинхронно и потенциально может быть вызван несколько раз подряд, но в немного другой ситуации.

- -

Важные события

- -

Web-браузеры определяют большое число событий, поэтому не практично описывать их все. Event Reference призван содержать список стандартных событий, используемых в современных браузерах.

- -

В общем случае, события различного вида выделяют, основываясь на объекте, который вызывает данное событие, включая:

- -
    -
  • объект window, на случай изменения размера браузера,
  • -
  • объект window.screen, на случай изменения положения устройства,
  • -
  • объект document, включая загрузку, модификацию, пользовательское взаимодействие и разгрузку страницы,
  • -
  • объект в DOM (объектная модель документа) дереве, включая пользовательское взаимодействие или изменения,
  • -
  • объект XMLHttpRequest, используемый для запросов сети, и
  • -
  • медиа-объекты, такие как audio и video, когда медиа-потоковые плееры изменяют состояние.
  • -
- -

хотя этот список на данный момент неполный.

- -

Некоторые события, которые стоит отметить:

- -
-

Примечание: Этот список событий будет нуждаться в доработке, чтобы соответствовать действительности; эта работа ожидает некоторой глобальной реорганизации в документе. Так же нужно найти хорошее объяснение событий, включая события во время загрузки страницы, таких, как частично описанных в этой статье  или  этом вопросе на  Stack Overflow.

-
- -
    -
  • глобальный объект window вызывает событие, называемое 'load', когда страница закончила рендеринг, подразумевая, что все ресурсы были скачаны и применены, так что скрипт был выполнен и изображения отображены,
  • -
  • глобальный объект window вызывает событие, называемое 'resize', когда высота или ширина окна браузера была изменена пользователем,
  • -
  • объект DOM document, представляющий HTML-документ, вызывает событие, называемое 'DOMContentLoaded', когда документ закончил загрузку,
  • -
  • объект узла DOM, такой как div или button, вызывающий событие, называемое 'click', когда пользователь нажимает кнопку мыши, пока её указатель находится поверх узла DOM на HTML-странице.
  • -
- - - -

Иерархия объекта событий

- -

Web-браузер определяет множество событий различного вида. Каждое описание включает, как структуру данных, передающуюся в обработчика, объект, который наследуется от объекта EventPrototype.

- -

Частичная диаграмма иерархии класса объекта событий:

- -
-

Примечание: Эта диаграмма неполная.

-
- -

- -

Web API Документация содержит страницу, описывающую объект событий, который так же включает известные события DOM, подклассы объекта Event.

- -

Документации

- -

Три ресурса на MDN (Mozilla Developer Network) частично полезные для программистов, желающих работать с событиями:

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index 76db9cbba2..682aa37417 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -592,7 +592,7 @@ /zh-CN/docs/DOM:window.onresize /zh-CN/docs/Web/API/GlobalEventHandlers/onresize /zh-CN/docs/DOM:window.open /zh-CN/docs/Web/API/Window/open /zh-CN/docs/DOM:window.openDialog /zh-CN/docs/Web/API/Window/openDialog -/zh-CN/docs/Detecting_device_orientation /zh-CN/docs/Web/API/Detecting_device_orientation +/zh-CN/docs/Detecting_device_orientation /zh-CN/docs/orphaned/Web/API/Detecting_device_orientation /zh-CN/docs/Developer_Guide /zh-CN/docs/Mozilla/Developer_guide /zh-CN/docs/Developer_Guide/Adding_APIs_to_the_navigator_object /zh-CN/docs/Mozilla/Developer_guide/Adding_APIs_to_the_navigator_object /zh-CN/docs/Developer_Guide/Source_Code /zh-CN/docs/Mozilla/Developer_guide/Source_Code @@ -1477,6 +1477,7 @@ /zh-CN/docs/Web/API/Coordinates/latitude /zh-CN/docs/Web/API/GeolocationCoordinates/latitude /zh-CN/docs/Web/API/DOMImplementation.createHTMLDocument /zh-CN/docs/Web/API/DOMImplementation/createHTMLDocument /zh-CN/docs/Web/API/DOMImplementation.hasFeature /zh-CN/docs/Web/API/DOMImplementation/hasFeature +/zh-CN/docs/Web/API/Detecting_device_orientation /zh-CN/docs/orphaned/Web/API/Detecting_device_orientation /zh-CN/docs/Web/API/DeviceAcceleration /zh-CN/docs/Web/API/DeviceMotionEventAcceleration /zh-CN/docs/Web/API/DeviceLightEvent/Using_light_events /zh-CN/docs/Web/API/Ambient_Light_Events /zh-CN/docs/Web/API/Document.querySelectorAll /zh-CN/docs/Web/API/Document/querySelectorAll @@ -1501,6 +1502,7 @@ /zh-CN/docs/Web/API/DocumentOrShadowRoot/getSelection /zh-CN/docs/Web/API/Document/getSelection /zh-CN/docs/Web/API/DocumentOrShadowRoot/pointerLockElement /zh-CN/docs/Web/API/Document/pointerLockElement /zh-CN/docs/Web/API/DocumentOrShadowRoot/styleSheets /zh-CN/docs/Web/API/Document/styleSheets +/zh-CN/docs/Web/API/Document_Object_Model/Events /zh-CN/docs/orphaned/Web/API/Document_Object_Model/Events /zh-CN/docs/Web/API/Document_Object_Model/Preface /zh-CN/docs/conflicting/Web/API/Document_Object_Model /zh-CN/docs/Web/API/Element.classList /zh-CN/docs/Web/API/Element/classList /zh-CN/docs/Web/API/Element.className /zh-CN/docs/Web/API/Element/className @@ -2264,11 +2266,15 @@ /zh-CN/docs/Web/Guide/CSS/媒体查询 /zh-CN/docs/Web/CSS/Media_Queries/Using_media_queries /zh-CN/docs/Web/Guide/DOM /zh-CN/docs/conflicting/Web/API/Document_Object_Model_dd00a71ceceac547ab464128db6bd8ef /zh-CN/docs/Web/Guide/DOM/Whitespace_in_the_DOM /zh-CN/docs/Web/API/Document_Object_Model/Whitespace +/zh-CN/docs/Web/Guide/Events /zh-CN/docs/orphaned/Web/Guide/Events /zh-CN/docs/Web/Guide/Events/Creating_and_triggering_events /zh-CN/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/zh-CN/docs/Web/Guide/Events/Event_handlers /zh-CN/docs/orphaned/Web/Guide/Events/Event_handlers /zh-CN/docs/Web/Guide/Events/Media_events /zh-CN/docs/orphaned/Web/Guide/Events/Media_events /zh-CN/docs/Web/Guide/Events/Mutation_events /zh-CN/docs/orphaned/Web/Guide/Events/Mutation_events +/zh-CN/docs/Web/Guide/Events/Orientation_and_motion_data_explained /zh-CN/docs/orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +/zh-CN/docs/Web/Guide/Events/Overview_of_Events_and_Handlers /zh-CN/docs/orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers /zh-CN/docs/Web/Guide/Events/Touch_events /zh-CN/docs/Web/API/Touch_events -/zh-CN/docs/Web/Guide/Events/事件回调 /zh-CN/docs/Web/Guide/Events/Event_handlers +/zh-CN/docs/Web/Guide/Events/事件回调 /zh-CN/docs/orphaned/Web/Guide/Events/Event_handlers /zh-CN/docs/Web/Guide/HTML /zh-CN/docs/Learn/HTML /zh-CN/docs/Web/Guide/HTML/A_basic_ray-caster /zh-CN/docs/Web/API/Canvas_API/A_basic_ray-caster /zh-CN/docs/Web/Guide/HTML/Canvas_tutorial /zh-CN/docs/Web/API/Canvas_API/Tutorial diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index 778081b0d1..83e03da7cf 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -9163,17 +9163,6 @@ "Lex.Huang" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2020-10-15T21:21:28.912Z", - "contributors": [ - "Carllllo", - "zwcloud", - "xgqfrms-GitHub", - "ziyunfei", - "fancy", - "princetoad@gmail.com" - ] - }, "Web/API/DeviceLightEvent": { "modified": "2020-10-15T21:34:11.102Z", "contributors": [ @@ -10393,17 +10382,6 @@ "Xagq123456" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-07-06T03:38:22.874Z", - "contributors": [ - "ridiculousjam", - "v-killer", - "SmallBusy", - "Noly1990", - "dongyu063", - "gavinkwoe" - ] - }, "Web/API/Document_Object_Model/Examples": { "modified": "2019-03-24T00:15:45.643Z", "contributors": [ @@ -28776,39 +28754,6 @@ "yan" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T23:20:12.541Z", - "contributors": [ - "Imagine-Tom", - "tcatche", - "NoDocCat", - "Tankunpeng", - "Jeremie" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2019-03-23T23:20:11.825Z", - "contributors": [ - "tcatche", - "Le-Fu", - "xgqfrms-GitHub", - "ziyunfei", - "Darrel.Hsu" - ] - }, - "Web/Guide/Events/Orientation_and_motion_data_explained": { - "modified": "2019-03-23T23:10:07.666Z", - "contributors": [ - "fancy" - ] - }, - "Web/Guide/Events/Overview_of_Events_and_Handlers": { - "modified": "2019-03-23T22:51:31.630Z", - "contributors": [ - "Song2017", - "FredWe" - ] - }, "Web/Guide/Graphics": { "modified": "2020-12-07T03:47:26.253Z", "contributors": [ @@ -50798,5 +50743,60 @@ "FredWe", "ReyCG_sub" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2020-10-15T21:21:28.912Z", + "contributors": [ + "Carllllo", + "zwcloud", + "xgqfrms-GitHub", + "ziyunfei", + "fancy", + "princetoad@gmail.com" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-07-06T03:38:22.874Z", + "contributors": [ + "ridiculousjam", + "v-killer", + "SmallBusy", + "Noly1990", + "dongyu063", + "gavinkwoe" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2019-03-23T23:20:11.825Z", + "contributors": [ + "tcatche", + "Le-Fu", + "xgqfrms-GitHub", + "ziyunfei", + "Darrel.Hsu" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T23:20:12.541Z", + "contributors": [ + "Imagine-Tom", + "tcatche", + "NoDocCat", + "Tankunpeng", + "Jeremie" + ] + }, + "orphaned/Web/Guide/Events/Orientation_and_motion_data_explained": { + "modified": "2019-03-23T23:10:07.666Z", + "contributors": [ + "fancy" + ] + }, + "orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers": { + "modified": "2019-03-23T22:51:31.630Z", + "contributors": [ + "Song2017", + "FredWe" + ] } } \ No newline at end of file diff --git a/files/zh-cn/orphaned/web/api/detecting_device_orientation/index.html b/files/zh-cn/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..84bf547bc9 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,319 @@ +--- +title: 检测设备方向 +slug: orphaned/Web/API/Detecting_device_orientation +tags: + - Detecting + - Detecting device orientation + - Device Orientation + - Motion + - 参考 + - 方向 + - 移动设备 + - 设备方向 +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +

{{SeeCompatTable}}

+ +

有越来越多的基于web的设备能够确定它们的方向; 也就是说,它们可以报告数据以指示基于重力方向的方向改变。特别地,手持设备如手机可以利用这些信息以自动旋转屏幕,保持内容直立,当设备旋转至横屏时(宽度大于高度),提供网页内容的横屏视图。

+ +

有两种Javascript事件负责处理设备方向信息。第一种是{{domxref("DeviceOrientationEvent")}},它会在加速度传感器检测到设备在方向上产生变化时触发。通过处理该事件传来的数据信息,让交互式地响应用户移动设备旋转和仰角变化成为可能。

+ +

第二种是{{domxref("DeviceMotionEvent")}},它会在加速度发生改变时触发。跟{{domxref("DeviceOrientationEvent")}}不同,{{domxref("DeviceMotionEvent")}}监听的是相应方向上加速度的变化。传感器通常都具有监听{{domxref("DeviceMotionEvent")}}的能力,包括笔记本中用于保护移动中的存储设备的传感器。{{domxref("DeviceOrientationEvent")}}事件更多见于移动设备中。

+ +

处理方向(orientation)事件

+ +

要接收设备方向变化信息,只需要监听{{ event("deviceorientation") }}事件:

+ +
+

注意:gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

注册完事件监听处理函数后(对应这个例子中的handleOrientation),监听函数会定期地接收到最新的设备方向数据。

+ +

方向事件对象中包含四个值:

+ +

{{ domxref("DeviceOrientationEvent.absolute") }}

+ +

{{ domxref("DeviceOrientationEvent.alpha") }}

+ +

{{ domxref("DeviceOrientationEvent.beta") }}

+ +

{{ domxref("DeviceOrientationEvent.gamma") }}

+ +

下面是一个事件处理函数的例子:

+ +
function handleOrientation(orientData) {
+  var absolute = orientData.absolute;
+  var alpha = orientData.alpha;
+  var beta = orientData.beta;
+  var gamma = orientData.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

相关值解释

+ +

关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。Orientation and motion data explained 这篇文章有更详细的描述,下面是对这篇文章的总结。

+ +
    +
  • {{ domxref("DeviceOrientationEvent.alpha") }} 表示设备沿z轴上的旋转角度,范围为0~360。
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }} 表示设备在x轴上的旋转角度,范围为-180~180。它描述的是设备由前向后旋转的情况。
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }} 表示设备在y轴上的旋转角度,范围为-90~90。它描述的是设备由左向右旋转的情况。
  • +
+ +

例子

+ +

这个例子会成功运行在支持检测自己方向的设备中的支持{{event("deviceorientation")}} 事件的浏览器中。

+ +

让我们想象一下有一个球在花园中:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+ +
+ +
+ +

花园只有200px宽(很小对吧),球在中央:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

现在,如果我们移动设备,球将随之移动:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positioning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+ +

输出结果:

+ +

这里以新窗口打开此示例;因为有些浏览器中的 {{event("deviceorientation")}} 事件不支持跨域。

+ +

+ +
+

警告: Chrome 和 Firefox 处理角度的机制不同,所以某些轴上的方向是相反的。

+
+ +

处理移动(motion)事件

+ +

移动事件的处理跟方向事件是一样的,除了他们有自己的事件名:{{ event("devicemotion") }}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +
+ +

真正不同的是做为参数传递给HandleMotion函数的{{ domxref("DeviceMotionEvent") }}对象所包含的信息。

+ +

这个对象包含四个属性:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

相关值解释

+ +

{{ domxref("DeviceMotionEvent") }}对象提供给web开发者设备在位置和方向上的改变速度的相关信息。这些变化信息是通过三个轴来体现的。(Orientation and motion data explained有更详细的说明。)

+ +

acceleration 和 accelerationIncludingGravity,都包含下面三个轴:

+ +
    +
  • x: 西向东
  • +
  • y: 南向北
  • +
  • z: 垂直地面
  • +
+ +

对于 rotationRate ,情况有点不同;三个轴的信息对应着以下三种情况:

+ +
    +
  • alpha: 设备沿着垂直于屏幕(对于桌面设备则是垂直于键盘)的轴的旋转速率
  • +
  • beta: 设备沿着屏幕(对于桌面设备则是键盘)左至右方向的轴的旋转速率(桌面设备相对于键盘)
  • +
  • gamma: 设备沿着屏幕(对于桌面设备则是键盘)下至上方向的轴的旋转速率
  • +
+ +

最后,interval 表示的是从设备获取数据的间隔时间,单位是毫秒。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容性

+ +

DeviceMotionEvent

+ +

{{Compat("api.DeviceMotionEvent")}}

+ +

DeviceOrientationEvent

+ +

{{Compat("api.DeviceOrientationEvent")}}

+ +

参见

+ + diff --git a/files/zh-cn/orphaned/web/api/document_object_model/events/index.html b/files/zh-cn/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..60ab48c450 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,81 @@ +--- +title: 事件及DOM +slug: orphaned/Web/API/Document_Object_Model/Events +tags: + - DOM + - events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

{{DefaultAPISidebar("DOM")}}

+ +

简介

+ +

这一章节介绍了DOM事件模型(DOM Event Model)。主要描述了事件(Event)接口本身以及DOM节点中的事件注册接口、事件监听接口,以及几个展示了多种事件接口之间相互关联的较长示例。

+ +

这里有一张非常不错的图表清晰地解释了在DOM3级事件草案(DOM Level 3 Events draft)中通过DOM处理事件流的三个阶段。

+ +

也可以通过示例章节的 示例5:事件传递 获取更多事件如何在DOM中流转的相关细节。

+ +

注册事件监听器

+ +

这里有3种方法来为一个DOM元素注册事件回调。

+ +

{{domxref("EventTarget.addEventListener")}}

+ +
// 假设 myButton 是一个按钮
+myButton.addEventListener('click', greet, false);
+function greet(event) {
+    // 打印并查看event对象
+    // 打印arguments,以防忽略了其他参数
+    console.log('greet: ' + arguments);
+    alert('Hello world');
+}
+
+ +

你应该在现代Web技术的页面中使用这个方法。

+ +

备注:IE 6-8 不支持这一方法,但提供了类似的API即 {{domxref("EventTarget.attachEvent")}} 用以替代。考虑到跨浏览器兼容性问题请使用有效的JS代码库。

+ +

更多细节可在 {{domxref("EventTarget.addEventListener")}} 参考页面中找到.

+ +

HTML 属性

+ +
<button onclick="alert('Hello world!')">
+
+ +

属性中的JS代码触发时通过event参数将Event类型对象传递过去的。其返回值以特殊的方式来处理,已经在HTML规范中被描述

+ +

应该尽量避免这种书写方式,这将使HTML变大并减少可读性。考虑到内容/结构及行为不能很好的分开,这将造成bug很难被找到。

+ +

DOM 元素属性

+ +
// 假设 myButton 是一个按钮
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

带有event参数的函数可以这样被定义。其返回值以特殊的方式来处理,已经在HTML规范中被描述。

+ +

这种方式的问题是每个事件及每个元素只能被设置一个回调。

+ +

访问事件接口

+ +

事件回调可以被绑定到包括DOM元素、文档、{{domxref("window")}} 等多种对象上。当一个事件被触发时,一个event对象将被创建并顺序的传递给事件监听者们。

+ +

 {{domxref("Event")}} 接口可以在回调函数内被访问到,通过被传递进来做为第一个参数的事件对象。以下这个简单例子展示了如何将事件对象传递给事件回调函数,同时可以在这个函数中使用。

+ +
function foo(evt) {
+  // evt参数自动分配事件对象
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ +

下级页面导航

+ + diff --git a/files/zh-cn/orphaned/web/guide/events/event_handlers/index.html b/files/zh-cn/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..52471bde8e --- /dev/null +++ b/files/zh-cn/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,181 @@ +--- +title: DOM 事件回调 +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

概要

+ +

Web平台提供了多种方式来获取 DOM events 的通知。两种常见的风格是:广义 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 和一组特定的on-event处理器。本页重点介绍后者如何工作的细节。

+ +

注册on-event 处理器

+ +

on-event 处理器是由DOM元素提供的一组属性,以帮助管理元素如何对事件反应。元素可以使可交互性的(例如链接,按钮,图像,表单)或者非可交互的(比如基本文档本身等)。事件是异性行为,像点击,检测到按下按键,获得焦点等。on-event 事件通常被相应地命名,诸如onclick,onkeypress,onfocus等。

+ +

你可以为一个给定的对象的某个特定事件(比如{{event("click")}})指定一个 on<...> 事件处理器,使用以下几种不同的方式:

+ +
    +
  • 在元素上使用 HTML {{Glossary("attribute")}} on{eventtype} ,例如:
    + <button onclick="return handleClick(event);">,
  • +
  • 或者通过 JavaScript 设置相应的属性( {{Glossary("property/JavaScript", "property")}}),例如:
    + document.getElementById("mybutton").onclick = function(event) { ... }.
  • +
+ +

注意,每个对象对于给定的事件只能有一个事件处理器(尽管该处理程序可以调用多个子处理器)。这就是为什么{{domxref("EventTarget.addEventListener", "addEventListener()")}} 通常是获得事件通知的更好方法,特别是当你希望彼此独立地应用各种事件处理程序时,即使对于相同的事件和/或相同的元素也是如此。

+ +

还要注意,事件处理器是自动调用的,而不是程序员的意志(尽管你可以使用像 mybutton.onclick(myevent); )。因为它们更多地用作可以分配真实处理器函数的占位符。

+ +

非元素对象

+ +

事件处理器也可以使用属性设置在生成事件的许多非元素对象上, 包括{{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, 和其他等等,例如:

+ +
xhr.onprogress = function() { ... }
+ +

细节

+ +

HTML的 on<...> 属性值 和相应JavaScript

+ +

通过 on<...> 元素属性注册的处理程序将通过相应的 on<...> 对象属性可用,相反,则不可用:

+ +
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
+
+<script>
+window.onload = function () {
+  var div = document.getElementById("a");
+  console.log("Attribute reflected as a property: ", div.onclick.toString());
+  // Prints: function onclick(event) { alert('old') }
+  div.onclick = function() { alert('new') };
+  console.log("Changed property to: ", div.onclick.toString());
+  // Prints: function () { alert('new') }
+  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
+  // Prints: alert('old')
+}
+</script>
+ +

由于历史原因,{{HTMLElement("body")}} 和 {{HTMLElement("frameset")}} 元素中的某些元素属性/对象属性实际上是在其父 {{domxref("Window")}} 对象上设置了事件处理器(这些 HTML 命名: onbluronerroronfocusonloadonscroll.)。

+ +

事件处理器的参数,this 绑定和返回值

+ +

当事件处理程序被指定为 HTML 属性,指定的代码被包装在有 以下参数 的函数中:

+ +
    +
  • event - 对于所有的事件处理器,除了 {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • +
  • eventsourcelinenocolno, and error 对于 {{domxref("GlobalEventHandlers.onerror", "onerror")}} 事件处理器。注意,event 参数实际上包含字符串的错误消息。
  • +
+ +

当事件处理器被调用,事件处理器内部的 this 关键字被设置为注册该事件处理器的 DOM 元素。更多信息查看 this 关键字文档 .

+ +

事件处理器的返回值决定了事件是否被取消。返回值的具体处理方式取决于事件的类型,更多信息查看 "The event handler processing algorithm" in the HTML specification.

+ +

什么时候调用事件处理程序

+ +

TBD (non-capturing listener)

+ +

术语 

+ +

术语 事件处理器(event handler) 可用于指:

+ +
    +
  • 注册的事件通知的任何函数或对象,
  • +
  • 或更具体地说,是通过HTML中的 on... 属性或web API中的属性来注册事件监听器的机制,例如 <button onclick="alert(this)"> window.onload = function() { /* ... */ }
  • +
+ +

在讨论各种监听事件的方法时:

+ +
    +
  •  事件侦听器(event listener)是指通过 {{domxref("EventTarget.addEventListener()")}} 注册的函数或对象,
  • +
  • 事件处理器(event handler)是指通过 on...  属性注册的函数。
  • +
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Firefox 9中的事件处理器的变动

+ +

为了更好地匹配规范,并提高跨浏览器兼容性,在Gecko 9.0 {{ geckoRelease("9.0") }} 中更改了基本级别事件处理器的实现方式。

+ +

具体来说,在过去,事件处理器没有被正确地实现为标准的IDL属性。在 Gecko 9.0,这一点被改变。因此,Gecko的事件处理程序的某些行为已经改变。特别地,它们现在含有为标准IDL属性行为的所有特性。在大多数情况下,这不应该影响网页或附加内容。然而,还有一些具体的事情需要注意。

+ +

检测事件处理程序属性的存在

+ +

你可以使用 JavaScript 的 in 运算符来检测事件处理器属性(例如,onload)的存在。例如:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

事件处理程序和原型

+ +

您不能设置或访问DOM原型对象上任何IDL定义的属性的值,这意味着您不能更改 Window.prototype.onload。在过去,事件处理程序(onload等)没有被实现为Gecko中的IDL属性,所以可以这样做,而现在你不能这样做,这提高了兼容性。

diff --git a/files/zh-cn/orphaned/web/guide/events/index.html b/files/zh-cn/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..1addfdd634 --- /dev/null +++ b/files/zh-cn/orphaned/web/guide/events/index.html @@ -0,0 +1,55 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

事件(Event)是指一种用于处理在网页的生命周期中发生的各种事件的异步调用的设计模式,也指一些不同种类事件的命名、描述和使用。

+ +

在 概述 中提供了对设计模式的介绍和现代Web浏览器中事件和处理程序的概述。

+ +

在 自定义事件 中介绍了如何创建自定义事件、注册监听自定义事件和如何在代码中触发自定义事件

+ +

接下来的内容描述了如何在Web浏览器中使用不同类型的事件。不幸的是,这些事件是随着Web浏览器的发展逐一定义的,所以,目前还没有一个令人满意的系统描述。

+ +

设备可以在Web浏览器运行时触发事件,例如,由于其在现实世界中的位置和方向的变化,在 page on orientation coordinate systems 和 page on the use of 3D transforms 被讨论,这与设备垂直方向的变化是不同的,但是类似的。

+ +

浏览器显示的 窗口 也可以触发事件, 例如,如果用户最大化窗口或以其他方式更改窗口大小。

+ +

网页的进程加载可以触发事件,响应下载,解析和呈现网页给用户的不同步骤的完成状态。

+ +

用户与网页内容的交互可能触发事件。用户交互触发的事件在浏览器设计的早期阶段发生,包括一个复杂的系统,定义了事件将被调用的顺序以及该序列可以被控制的方式。不同类型的用户交互驱动的事件包括:

+ + + +

 

+ +

网页的修改结构或内容可能会引发一些事件,如解释的突变事件页,但使用这些事件也有利于较轻的被弃用突变观察员的做法。

+ +

嵌入在HTML文档中媒体流可能会触发某些事件,如媒体事件页面中所述。

+ +

网页发出的网络请求可能会触发一些事件。

+ +

还有许多网页浏览器定义的其他事件还不包括在本指南中。

+ +
+

注意: 本是件开发指南还需要大量的工作,结构需要重新组织,页面重写。我们希望你所需要知道的一切事情都会在这里。

+
+ +

Docs

+ +

{{LandingPageListSubpages}}

diff --git a/files/zh-cn/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html b/files/zh-cn/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..b3c1f357a0 --- /dev/null +++ b/files/zh-cn/orphaned/web/guide/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,45 @@ +--- +title: Orientation 和 motion 数据解释 +slug: orphaned/Web/Guide/Events/Orientation_and_motion_data_explained +translation_of: Web/Guide/Events/Orientation_and_motion_data_explained +original_slug: Web/Guide/Events/Orientation_and_motion_data_explained +--- +

{{ Draft() }}

+

总言

+

当我们要使用orientation和motion事件时,理解浏览器给我们的相关值是什么意思就显的相当重要了。这篇文章会详细介绍在用的坐标系统并会教你如何全用它们。

+
+

警告: 目前, Firefox 和 Chrome 处理坐标的方式不同。 在使用它们的时候要多加注意.

+
+

坐标系

+

坐标系是一种描述物体位置的系统,它包含三个轴(X,Y,Z),三个轴共同描述了物体相对于参照物的位置信息。当我们使用orientation和motion事件时会接触到两种坐标系统。

+

地球坐标系

+

地球坐标系是相对于地心的,也就是说,它的轴是基于重力方向和磁场北方向。我们使用大写的X,Y,Z来描述地球坐标系的轴。

+
    +
  • X轴沿着地平面,垂直于Y轴,向东为正,向西为负。
  • +
  • Y轴沿着地平面,向北(北极,不是磁场北)为正,向南为负。
  • +
  • Z轴垂直于地平面,想象成一条线连接着设备跟地心。背对地心的方向为正,指向地心的方向为负。
  • +
+

设备坐标系

+

设备坐标系是相对于设备中心的。我们使用小写的x,y,z来描述它的轴。

+

,axes.png

+
    +
  • x轴沿着屏幕表面,向右为正,向左为负。
  • +
  • y轴沿着屏幕表面,向上为正,向下为负。
  • +
  • z轴垂直屏幕表面或键盘,远离屏幕的方向为正。
  • +
+
+ 注意:对于手机或平台而言,这里的设备方向总是相对于屏幕的标准方向,大部分是“竖屏”方向。而对于笔记本电脑来说,设备方向是相对于键盘的。如果你想检测设备方向变化来进行补偿调整,你可以使用orientationchange事件。
+

旋转(Rotation)

+

旋转描述的是设备在设备坐标系跟地球坐标系中任意轴上的差异值,用角度表示。

+

Alpha

+

围绕z轴旋转设备将使alpha角度值发生变化:

+

alpha.png

+

alpha为0°时表示设备的顶部正指北极方向,当设备向左旋转时,alpha将增加。

+

Beta

+

围绕x轴旋转,也就是前后旋转,将使beta值发生改变:

+

beta.png

+

当beta为0° 时表示设备顶部和底部与地表面的距离是一样的,当设备向前翻转时,beta递增到180°,向后翻转递减到-180°。

+

Gamma

+

当围绕y轴旋转,也就是左右倾斜设备时,将使gamma值发生改变:

+

gamma.png

+

gamma等于0°表示设备左右两边与地表面的距离相等,当设备向右翻转时,gamma递增到90° ,向左翻转时,递减到-90°。

diff --git a/files/zh-cn/orphaned/web/guide/events/overview_of_events_and_handlers/index.html b/files/zh-cn/orphaned/web/guide/events/overview_of_events_and_handlers/index.html new file mode 100644 index 0000000000..88a0ff78ec --- /dev/null +++ b/files/zh-cn/orphaned/web/guide/events/overview_of_events_and_handlers/index.html @@ -0,0 +1,136 @@ +--- +title: Overview of Events and Handlers +slug: orphaned/Web/Guide/Events/Overview_of_Events_and_Handlers +translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers +original_slug: Web/Guide/Events/Overview_of_Events_and_Handlers +--- +
+

事件和事件处理的概述解释了用于响应在Web页面时间发生的事件的代码设计模式,并总结了由现代Web浏览器处理的此类事件的类型。

+
+ +

 

+ +

事件和事件处理提供核心技术JavaScript的反应时间的一个网页的用户保持开放的过程中发生的事件,包括发生在一个页面正在准备显示事件,与网页的内容由于用户交互事件,到设备上浏览器运行相关的事件,或事件由于其他原因如媒体流的播放或动画时间。

+ +

事件和事件处理提供核心技术JavaScript的反应时间的一个网页的用户保持开放的过程中发生的事件,包括发生在一个页面正在准备显示事件,与网页的内容由于用户交互事件,到设备上浏览器运行相关的事件,或事件由于其他原因如媒体流的播放或动画时间。

+ +

 

+ +

事件和事件处理成为Web编程的核心,添加了浏览器的语言,伴随着浏览器从呈现和加载页面呈现到事件驱动、基于回流的页面渲染的转换结构的切换。最初,浏览器等待,直到它们接收到与页面相关的所有资源,解析、处理、绘制并向用户呈现页面。显示的页面保持不变,直到浏览器请求一个新页面为止。随着动态页面呈现的改变,浏览器在处理、绘制、呈现内容和等待一些新的事件触发之间不断循环。事件触发器包括完成网络上资源的加载,例如,下载一个现在可以在屏幕上绘制的图像,完成由浏览器解析资源的过程,例如处理页面的HTML内容、用户与页面内容的交互,例如单击按钮。道格拉斯克罗克福德的几个讲座有效地解释了这种变化,特别是他说的,一个不方便的API:DOM的理论,解释了原来的浏览器流流量的变化

+ +
A comparison of the sequential and event-driven browser load sequences.
+ +

到事件驱动的浏览器。后一种方法将最后一个步骤从单个流变为一个永久循环,在接下来的步骤中,等待和处理新事件的发生。后一种方法的创新允许在资源尚未获得的情况下部分地呈现页面;该方法还允许使用JavaScript驱动的事件驱动操作。(可以从多个渠道获得,包括这一个)。目前,JavaScript代码的所有执行环境都使用事件和事件处理。

+ +

事件设计模式

+ +

事件系统的核心是简单的编程设计模式。模式从一个事件和一个事件的协议开始:

+ +
    +
  • 事件使用的名称字符串,
  • +
  • 用于表示该事件的关键属性的数据结构的类型,以及
  • +
  • 将“发出”该事件的JavaScript对象。
  • +
+ +

该模式的实现

+ +
    +
  • 定义一个JavaScript函数,它作为一个参数,被商定的数据结构,以及
  • +
  • 使用将发出事件的对象使用名称字符串注册该函数。
  • +
+ +

该功能称为“听众”或“与名称interchangibly处理”。这一模式可以很容易地使用完全自定义代码,如文章中关于自定义事件的说明所述。这种模式也被现代Web浏览器所使用,它定义了响应用户输入或浏览器活动而发出的许多事件。

+ +

现代Web浏览器使用标准化方法跟踪事件模式。浏览器使用的数据结构对于事件的性质,从eventprototype对象派生对象。浏览器使用为功能,将处理这些数据结构的方法称为addEventListener期望作为参数的字符串类型的名称和事件处理函数的注册方法。最后,浏览器定义了大量的对象作为事件发射器,并定义了由对象生成的各种各样的事件类型。

+ +

按钮的事件处理程序演示

+ +

例如,浏览器按钮元素意在发出事件命名为'click'响应鼠标单击或当显示在触摸敏感表面,一个手指单击。我们可以在HTML页面中定义一个按钮:

+ +
<button id="buttonOne">Click here to emit a 'click' event</button>
+ +

而且,在JavaScript代码中,我们可以首先定义一个函数来监听“click”事件:

+ +
var example_click_handler = function (ev){
+    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
+    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
+};
+ +

第二,我们使用按钮对象注册我们的函数,无论是在脚本方面,还是使用HTML页面的DOM(文档对象模型)表示:

+ +
var buttonDOMElement = document.querySelector('#buttonOne');
+buttonDOMElement.addEventListener('click', example_click_handler);
+ +

或在HTML页面中添加功能的“onclick”属性的值,虽然这第二种方法通常只用于非常简单的网页。

+ +

{{ EmbedLiveSample('Button_Event_Handler') }}

+ +

这段代码依赖,有一种叫做“点击”事件,称任何监听协议(或处理)与一个事件对象参数的函数(实际上,在这种情况下,衍生的MouseEvent对象),将使用HTML按钮元素在用户交互。代码没有明显影响到用户的按钮,可以通过将鼠标指针放在HTML按钮,点击鼠标左键,或用手指或手写笔点上面的HTML按钮屏幕互动;当这种情况发生时,该buttonDOMElement  JavaScript对象会调用example_click_handler功能与事件对象作为参数。函数将依次执行程序员选择的任何操作,在这种情况下,打开一个HTML警报对话框。注意,处理程序对‘ev’对象有访问权,因为它作为参数传递;对象有关于事件的信息,特别是事件发生的时间。

+ +

作为第二个例子,集成到Web页面中的许多现代JavaScript被封装到事件函数调用中,以确保代码只在HTML被处理并可用于更改或装饰时执行。例如,代码可以附加为:

+ +
var funcInit = function(){
+    // user code goes here and can safetly address all the HTML elements from the page
+    // since the document has successfully been 'loaded'
+}
+document.addEventListener('DOMContentLoaded', funcInit);
+
+
+ +

所以,此代码只会在文档对象发出“DOMContentLoaded“事件因为HTML解析完毕和javascript对象创建代表每个HTML文档的节点执行。注意,在这个例子中,代码甚至没有为函数命名事件参数,因为代码永远不需要使用描述事件的数据结构;相反,代码只需要等待运行,直到事件发生之后。

+ +

因此,该模式易于学习和实现。事件的困难来自于学习在现代Web浏览器中生成的各种各样的事件。学习如何编写处理程序函数也有一些微妙之处,因为这些代码异步工作,可能会重复运行,但情况略有不同。

+ +

值得注意的事件

+ +

Web浏览器定义了大量事件,所以列出所有事件是不现实的。事件引用试图维护现代Web浏览器中使用的标准事件列表。

+ +

一般来说,我们可以根据事件的对象来区分不同类型的事件,包括:

+ +
    +
  • 窗口window对象,如由于调整浏览器大小,
  • +
  • window.screen对象,如由于设备的方向变化,
  • +
  • 文档document对象,包括页面的加载、修改、用户交互和卸载,
  • +
  • DOM(文档对象模型)树中的对象,包括用户交互或修改,
  • +
  • XMLHttpRequest对象用于网络的要求,和
  • +
  • 当媒体流播放器改变状态时,诸如音频audio和视频video等媒体对象。
  • +
+ +

虽然这个列表目前不完整。

+ +

一些值得注意的事件是:

+ +
+

Note: 这份清单将需要相关的工作;这项工作正在等待一些关于文件的全球重组工作。这还需要找到在页面加载期间所涉及到的事件的良好解释,如部分讨论在  this web page 或 this Stack Overflow question.

+
+ +
    +
  • 当页面完成渲染时,全局对象窗口window发出一个名为“load”的事件,这意味着所有资源都已下载并执行,以便运行脚本并显示图像,
  • +
  • 当浏览器窗口window的高度或宽度被用户更改时,全局对象窗口发出一个称为“resize”的事件,
  • +
  • DOM文档对象代表了HTML文件发出一个事件被称为”DOMContentLoaded“当文档加载完毕,
  • +
  • 当鼠标指针位于HTML页面的DOM节点顶部时,当用户按下鼠标按钮时,如div或button的DOM节点对象发出一个名为“click”的事件。
  • +
+ +

事件对象层次结构

+ +

Web浏览器定义了许多不同类型的事件。每个定义包括,作为数据结构传递给处理函数,一个对象继承自EventPrototype对象。

+ +

事件对象类层次结构的部分图是:

+ +
+

Note: 下面的图标是不完整的.

+
+ +

+ +

Web API文档包含定义事件对象的页面,该事件对象还包括事件对象已知的DOM事件子类。

+ +

文档

+ +

下面是三个链接对MDN(Mozilla开发者网络)网站程序员从事于事件相关的开发是特别有用的:

+ + diff --git a/files/zh-cn/web/api/detecting_device_orientation/index.html b/files/zh-cn/web/api/detecting_device_orientation/index.html deleted file mode 100644 index d6afcb16f6..0000000000 --- a/files/zh-cn/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,318 +0,0 @@ ---- -title: 检测设备方向 -slug: Web/API/Detecting_device_orientation -tags: - - Detecting - - Detecting device orientation - - Device Orientation - - Motion - - 参考 - - 方向 - - 移动设备 - - 设备方向 -translation_of: Web/API/Detecting_device_orientation ---- -

{{SeeCompatTable}}

- -

有越来越多的基于web的设备能够确定它们的方向; 也就是说,它们可以报告数据以指示基于重力方向的方向改变。特别地,手持设备如手机可以利用这些信息以自动旋转屏幕,保持内容直立,当设备旋转至横屏时(宽度大于高度),提供网页内容的横屏视图。

- -

有两种Javascript事件负责处理设备方向信息。第一种是{{domxref("DeviceOrientationEvent")}},它会在加速度传感器检测到设备在方向上产生变化时触发。通过处理该事件传来的数据信息,让交互式地响应用户移动设备旋转和仰角变化成为可能。

- -

第二种是{{domxref("DeviceMotionEvent")}},它会在加速度发生改变时触发。跟{{domxref("DeviceOrientationEvent")}}不同,{{domxref("DeviceMotionEvent")}}监听的是相应方向上加速度的变化。传感器通常都具有监听{{domxref("DeviceMotionEvent")}}的能力,包括笔记本中用于保护移动中的存储设备的传感器。{{domxref("DeviceOrientationEvent")}}事件更多见于移动设备中。

- -

处理方向(orientation)事件

- -

要接收设备方向变化信息,只需要监听{{ event("deviceorientation") }}事件:

- -
-

注意:gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

注册完事件监听处理函数后(对应这个例子中的handleOrientation),监听函数会定期地接收到最新的设备方向数据。

- -

方向事件对象中包含四个值:

- -

{{ domxref("DeviceOrientationEvent.absolute") }}

- -

{{ domxref("DeviceOrientationEvent.alpha") }}

- -

{{ domxref("DeviceOrientationEvent.beta") }}

- -

{{ domxref("DeviceOrientationEvent.gamma") }}

- -

下面是一个事件处理函数的例子:

- -
function handleOrientation(orientData) {
-  var absolute = orientData.absolute;
-  var alpha = orientData.alpha;
-  var beta = orientData.beta;
-  var gamma = orientData.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

相关值解释

- -

关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。Orientation and motion data explained 这篇文章有更详细的描述,下面是对这篇文章的总结。

- -
    -
  • {{ domxref("DeviceOrientationEvent.alpha") }} 表示设备沿z轴上的旋转角度,范围为0~360。
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }} 表示设备在x轴上的旋转角度,范围为-180~180。它描述的是设备由前向后旋转的情况。
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }} 表示设备在y轴上的旋转角度,范围为-90~90。它描述的是设备由左向右旋转的情况。
  • -
- -

例子

- -

这个例子会成功运行在支持检测自己方向的设备中的支持{{event("deviceorientation")}} 事件的浏览器中。

- -

让我们想象一下有一个球在花园中:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
- -
- -
- -

花园只有200px宽(很小对吧),球在中央:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -

现在,如果我们移动设备,球将随之移动:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positioning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
-
- -
- -
- -
- -
- -
- -
- -
-
- -

输出结果:

- -

这里以新窗口打开此示例;因为有些浏览器中的 {{event("deviceorientation")}} 事件不支持跨域。

- -

- -
-

警告: Chrome 和 Firefox 处理角度的机制不同,所以某些轴上的方向是相反的。

-
- -

处理移动(motion)事件

- -

移动事件的处理跟方向事件是一样的,除了他们有自己的事件名:{{ event("devicemotion") }}

- -
window.addEventListener("devicemotion", handleMotion, true);
- -
- -

真正不同的是做为参数传递给HandleMotion函数的{{ domxref("DeviceMotionEvent") }}对象所包含的信息。

- -

这个对象包含四个属性:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

相关值解释

- -

{{ domxref("DeviceMotionEvent") }}对象提供给web开发者设备在位置和方向上的改变速度的相关信息。这些变化信息是通过三个轴来体现的。(Orientation and motion data explained有更详细的说明。)

- -

acceleration 和 accelerationIncludingGravity,都包含下面三个轴:

- -
    -
  • x: 西向东
  • -
  • y: 南向北
  • -
  • z: 垂直地面
  • -
- -

对于 rotationRate ,情况有点不同;三个轴的信息对应着以下三种情况:

- -
    -
  • alpha: 设备沿着垂直于屏幕(对于桌面设备则是垂直于键盘)的轴的旋转速率
  • -
  • beta: 设备沿着屏幕(对于桌面设备则是键盘)左至右方向的轴的旋转速率(桌面设备相对于键盘)
  • -
  • gamma: 设备沿着屏幕(对于桌面设备则是键盘)下至上方向的轴的旋转速率
  • -
- -

最后,interval 表示的是从设备获取数据的间隔时间,单位是毫秒。

- -

规范

- - - - - - - - - - - - - - - - -
规范状态注释
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
- -

浏览器兼容性

- -

DeviceMotionEvent

- -

{{Compat("api.DeviceMotionEvent")}}

- -

DeviceOrientationEvent

- -

{{Compat("api.DeviceOrientationEvent")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/document_object_model/events/index.html b/files/zh-cn/web/api/document_object_model/events/index.html deleted file mode 100644 index b2dc638d82..0000000000 --- a/files/zh-cn/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: 事件及DOM -slug: Web/API/Document_Object_Model/Events -tags: - - DOM - - events -translation_of: Web/API/Document_Object_Model/Events ---- -

{{DefaultAPISidebar("DOM")}}

- -

简介

- -

这一章节介绍了DOM事件模型(DOM Event Model)。主要描述了事件(Event)接口本身以及DOM节点中的事件注册接口、事件监听接口,以及几个展示了多种事件接口之间相互关联的较长示例。

- -

这里有一张非常不错的图表清晰地解释了在DOM3级事件草案(DOM Level 3 Events draft)中通过DOM处理事件流的三个阶段。

- -

也可以通过示例章节的 示例5:事件传递 获取更多事件如何在DOM中流转的相关细节。

- -

注册事件监听器

- -

这里有3种方法来为一个DOM元素注册事件回调。

- -

{{domxref("EventTarget.addEventListener")}}

- -
// 假设 myButton 是一个按钮
-myButton.addEventListener('click', greet, false);
-function greet(event) {
-    // 打印并查看event对象
-    // 打印arguments,以防忽略了其他参数
-    console.log('greet: ' + arguments);
-    alert('Hello world');
-}
-
- -

你应该在现代Web技术的页面中使用这个方法。

- -

备注:IE 6-8 不支持这一方法,但提供了类似的API即 {{domxref("EventTarget.attachEvent")}} 用以替代。考虑到跨浏览器兼容性问题请使用有效的JS代码库。

- -

更多细节可在 {{domxref("EventTarget.addEventListener")}} 参考页面中找到.

- -

HTML 属性

- -
<button onclick="alert('Hello world!')">
-
- -

属性中的JS代码触发时通过event参数将Event类型对象传递过去的。其返回值以特殊的方式来处理,已经在HTML规范中被描述

- -

应该尽量避免这种书写方式,这将使HTML变大并减少可读性。考虑到内容/结构及行为不能很好的分开,这将造成bug很难被找到。

- -

DOM 元素属性

- -
// 假设 myButton 是一个按钮
-myButton.onclick = function(event){alert('Hello world');};
-
- -

带有event参数的函数可以这样被定义。其返回值以特殊的方式来处理,已经在HTML规范中被描述。

- -

这种方式的问题是每个事件及每个元素只能被设置一个回调。

- -

访问事件接口

- -

事件回调可以被绑定到包括DOM元素、文档、{{domxref("window")}} 等多种对象上。当一个事件被触发时,一个event对象将被创建并顺序的传递给事件监听者们。

- -

 {{domxref("Event")}} 接口可以在回调函数内被访问到,通过被传递进来做为第一个参数的事件对象。以下这个简单例子展示了如何将事件对象传递给事件回调函数,同时可以在这个函数中使用。

- -
function foo(evt) {
-  // evt参数自动分配事件对象
-  alert(evt);
-}
-table_el.onclick = foo;
-
- -

下级页面导航

- - diff --git a/files/zh-cn/web/guide/events/event_handlers/index.html b/files/zh-cn/web/guide/events/event_handlers/index.html deleted file mode 100644 index 279d77159c..0000000000 --- a/files/zh-cn/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: DOM 事件回调 -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers ---- -

概要

- -

Web平台提供了多种方式来获取 DOM events 的通知。两种常见的风格是:广义 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 和一组特定的on-event处理器。本页重点介绍后者如何工作的细节。

- -

注册on-event 处理器

- -

on-event 处理器是由DOM元素提供的一组属性,以帮助管理元素如何对事件反应。元素可以使可交互性的(例如链接,按钮,图像,表单)或者非可交互的(比如基本文档本身等)。事件是异性行为,像点击,检测到按下按键,获得焦点等。on-event 事件通常被相应地命名,诸如onclick,onkeypress,onfocus等。

- -

你可以为一个给定的对象的某个特定事件(比如{{event("click")}})指定一个 on<...> 事件处理器,使用以下几种不同的方式:

- -
    -
  • 在元素上使用 HTML {{Glossary("attribute")}} on{eventtype} ,例如:
    - <button onclick="return handleClick(event);">,
  • -
  • 或者通过 JavaScript 设置相应的属性( {{Glossary("property/JavaScript", "property")}}),例如:
    - document.getElementById("mybutton").onclick = function(event) { ... }.
  • -
- -

注意,每个对象对于给定的事件只能有一个事件处理器(尽管该处理程序可以调用多个子处理器)。这就是为什么{{domxref("EventTarget.addEventListener", "addEventListener()")}} 通常是获得事件通知的更好方法,特别是当你希望彼此独立地应用各种事件处理程序时,即使对于相同的事件和/或相同的元素也是如此。

- -

还要注意,事件处理器是自动调用的,而不是程序员的意志(尽管你可以使用像 mybutton.onclick(myevent); )。因为它们更多地用作可以分配真实处理器函数的占位符。

- -

非元素对象

- -

事件处理器也可以使用属性设置在生成事件的许多非元素对象上, 包括{{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, 和其他等等,例如:

- -
xhr.onprogress = function() { ... }
- -

细节

- -

HTML的 on<...> 属性值 和相应JavaScript

- -

通过 on<...> 元素属性注册的处理程序将通过相应的 on<...> 对象属性可用,相反,则不可用:

- -
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
-
-<script>
-window.onload = function () {
-  var div = document.getElementById("a");
-  console.log("Attribute reflected as a property: ", div.onclick.toString());
-  // Prints: function onclick(event) { alert('old') }
-  div.onclick = function() { alert('new') };
-  console.log("Changed property to: ", div.onclick.toString());
-  // Prints: function () { alert('new') }
-  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
-  // Prints: alert('old')
-}
-</script>
- -

由于历史原因,{{HTMLElement("body")}} 和 {{HTMLElement("frameset")}} 元素中的某些元素属性/对象属性实际上是在其父 {{domxref("Window")}} 对象上设置了事件处理器(这些 HTML 命名: onbluronerroronfocusonloadonscroll.)。

- -

事件处理器的参数,this 绑定和返回值

- -

当事件处理程序被指定为 HTML 属性,指定的代码被包装在有 以下参数 的函数中:

- -
    -
  • event - 对于所有的事件处理器,除了 {{domxref("GlobalEventHandlers.onerror", "onerror")}}.
  • -
  • eventsourcelinenocolno, and error 对于 {{domxref("GlobalEventHandlers.onerror", "onerror")}} 事件处理器。注意,event 参数实际上包含字符串的错误消息。
  • -
- -

当事件处理器被调用,事件处理器内部的 this 关键字被设置为注册该事件处理器的 DOM 元素。更多信息查看 this 关键字文档 .

- -

事件处理器的返回值决定了事件是否被取消。返回值的具体处理方式取决于事件的类型,更多信息查看 "The event handler processing algorithm" in the HTML specification.

- -

什么时候调用事件处理程序

- -

TBD (non-capturing listener)

- -

术语 

- -

术语 事件处理器(event handler) 可用于指:

- -
    -
  • 注册的事件通知的任何函数或对象,
  • -
  • 或更具体地说,是通过HTML中的 on... 属性或web API中的属性来注册事件监听器的机制,例如 <button onclick="alert(this)"> window.onload = function() { /* ... */ }
  • -
- -

在讨论各种监听事件的方法时:

- -
    -
  •  事件侦听器(event listener)是指通过 {{domxref("EventTarget.addEventListener()")}} 注册的函数或对象,
  • -
  • 事件处理器(event handler)是指通过 on...  属性注册的函数。
  • -
- -

规范

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}} 
- -

浏览器兼容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -

Firefox 9中的事件处理器的变动

- -

为了更好地匹配规范,并提高跨浏览器兼容性,在Gecko 9.0 {{ geckoRelease("9.0") }} 中更改了基本级别事件处理器的实现方式。

- -

具体来说,在过去,事件处理器没有被正确地实现为标准的IDL属性。在 Gecko 9.0,这一点被改变。因此,Gecko的事件处理程序的某些行为已经改变。特别地,它们现在含有为标准IDL属性行为的所有特性。在大多数情况下,这不应该影响网页或附加内容。然而,还有一些具体的事情需要注意。

- -

检测事件处理程序属性的存在

- -

你可以使用 JavaScript 的 in 运算符来检测事件处理器属性(例如,onload)的存在。例如:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

事件处理程序和原型

- -

您不能设置或访问DOM原型对象上任何IDL定义的属性的值,这意味着您不能更改 Window.prototype.onload。在过去,事件处理程序(onload等)没有被实现为Gecko中的IDL属性,所以可以这样做,而现在你不能这样做,这提高了兼容性。

diff --git a/files/zh-cn/web/guide/events/index.html b/files/zh-cn/web/guide/events/index.html deleted file mode 100644 index e885cdd8b7..0000000000 --- a/files/zh-cn/web/guide/events/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

事件(Event)是指一种用于处理在网页的生命周期中发生的各种事件的异步调用的设计模式,也指一些不同种类事件的命名、描述和使用。

- -

在 概述 中提供了对设计模式的介绍和现代Web浏览器中事件和处理程序的概述。

- -

在 自定义事件 中介绍了如何创建自定义事件、注册监听自定义事件和如何在代码中触发自定义事件

- -

接下来的内容描述了如何在Web浏览器中使用不同类型的事件。不幸的是,这些事件是随着Web浏览器的发展逐一定义的,所以,目前还没有一个令人满意的系统描述。

- -

设备可以在Web浏览器运行时触发事件,例如,由于其在现实世界中的位置和方向的变化,在 page on orientation coordinate systems 和 page on the use of 3D transforms 被讨论,这与设备垂直方向的变化是不同的,但是类似的。

- -

浏览器显示的 窗口 也可以触发事件, 例如,如果用户最大化窗口或以其他方式更改窗口大小。

- -

网页的进程加载可以触发事件,响应下载,解析和呈现网页给用户的不同步骤的完成状态。

- -

用户与网页内容的交互可能触发事件。用户交互触发的事件在浏览器设计的早期阶段发生,包括一个复杂的系统,定义了事件将被调用的顺序以及该序列可以被控制的方式。不同类型的用户交互驱动的事件包括:

- - - -

 

- -

网页的修改结构或内容可能会引发一些事件,如解释的突变事件页,但使用这些事件也有利于较轻的被弃用突变观察员的做法。

- -

嵌入在HTML文档中媒体流可能会触发某些事件,如媒体事件页面中所述。

- -

网页发出的网络请求可能会触发一些事件。

- -

还有许多网页浏览器定义的其他事件还不包括在本指南中。

- -
-

注意: 本是件开发指南还需要大量的工作,结构需要重新组织,页面重写。我们希望你所需要知道的一切事情都会在这里。

-
- -

Docs

- -

{{LandingPageListSubpages}}

diff --git a/files/zh-cn/web/guide/events/orientation_and_motion_data_explained/index.html b/files/zh-cn/web/guide/events/orientation_and_motion_data_explained/index.html deleted file mode 100644 index f817c71bab..0000000000 --- a/files/zh-cn/web/guide/events/orientation_and_motion_data_explained/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Orientation 和 motion 数据解释 -slug: Web/Guide/Events/Orientation_and_motion_data_explained -translation_of: Web/Guide/Events/Orientation_and_motion_data_explained ---- -

{{ Draft() }}

-

总言

-

当我们要使用orientation和motion事件时,理解浏览器给我们的相关值是什么意思就显的相当重要了。这篇文章会详细介绍在用的坐标系统并会教你如何全用它们。

-
-

警告: 目前, Firefox 和 Chrome 处理坐标的方式不同。 在使用它们的时候要多加注意.

-
-

坐标系

-

坐标系是一种描述物体位置的系统,它包含三个轴(X,Y,Z),三个轴共同描述了物体相对于参照物的位置信息。当我们使用orientation和motion事件时会接触到两种坐标系统。

-

地球坐标系

-

地球坐标系是相对于地心的,也就是说,它的轴是基于重力方向和磁场北方向。我们使用大写的X,Y,Z来描述地球坐标系的轴。

-
    -
  • X轴沿着地平面,垂直于Y轴,向东为正,向西为负。
  • -
  • Y轴沿着地平面,向北(北极,不是磁场北)为正,向南为负。
  • -
  • Z轴垂直于地平面,想象成一条线连接着设备跟地心。背对地心的方向为正,指向地心的方向为负。
  • -
-

设备坐标系

-

设备坐标系是相对于设备中心的。我们使用小写的x,y,z来描述它的轴。

-

,axes.png

-
    -
  • x轴沿着屏幕表面,向右为正,向左为负。
  • -
  • y轴沿着屏幕表面,向上为正,向下为负。
  • -
  • z轴垂直屏幕表面或键盘,远离屏幕的方向为正。
  • -
-
- 注意:对于手机或平台而言,这里的设备方向总是相对于屏幕的标准方向,大部分是“竖屏”方向。而对于笔记本电脑来说,设备方向是相对于键盘的。如果你想检测设备方向变化来进行补偿调整,你可以使用orientationchange事件。
-

旋转(Rotation)

-

旋转描述的是设备在设备坐标系跟地球坐标系中任意轴上的差异值,用角度表示。

-

Alpha

-

围绕z轴旋转设备将使alpha角度值发生变化:

-

alpha.png

-

alpha为0°时表示设备的顶部正指北极方向,当设备向左旋转时,alpha将增加。

-

Beta

-

围绕x轴旋转,也就是前后旋转,将使beta值发生改变:

-

beta.png

-

当beta为0° 时表示设备顶部和底部与地表面的距离是一样的,当设备向前翻转时,beta递增到180°,向后翻转递减到-180°。

-

Gamma

-

当围绕y轴旋转,也就是左右倾斜设备时,将使gamma值发生改变:

-

gamma.png

-

gamma等于0°表示设备左右两边与地表面的距离相等,当设备向右翻转时,gamma递增到90° ,向左翻转时,递减到-90°。

diff --git a/files/zh-cn/web/guide/events/overview_of_events_and_handlers/index.html b/files/zh-cn/web/guide/events/overview_of_events_and_handlers/index.html deleted file mode 100644 index 87ddd75dde..0000000000 --- a/files/zh-cn/web/guide/events/overview_of_events_and_handlers/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Overview of Events and Handlers -slug: Web/Guide/Events/Overview_of_Events_and_Handlers -translation_of: Web/Guide/Events/Overview_of_Events_and_Handlers ---- -
-

事件和事件处理的概述解释了用于响应在Web页面时间发生的事件的代码设计模式,并总结了由现代Web浏览器处理的此类事件的类型。

-
- -

 

- -

事件和事件处理提供核心技术JavaScript的反应时间的一个网页的用户保持开放的过程中发生的事件,包括发生在一个页面正在准备显示事件,与网页的内容由于用户交互事件,到设备上浏览器运行相关的事件,或事件由于其他原因如媒体流的播放或动画时间。

- -

事件和事件处理提供核心技术JavaScript的反应时间的一个网页的用户保持开放的过程中发生的事件,包括发生在一个页面正在准备显示事件,与网页的内容由于用户交互事件,到设备上浏览器运行相关的事件,或事件由于其他原因如媒体流的播放或动画时间。

- -

 

- -

事件和事件处理成为Web编程的核心,添加了浏览器的语言,伴随着浏览器从呈现和加载页面呈现到事件驱动、基于回流的页面渲染的转换结构的切换。最初,浏览器等待,直到它们接收到与页面相关的所有资源,解析、处理、绘制并向用户呈现页面。显示的页面保持不变,直到浏览器请求一个新页面为止。随着动态页面呈现的改变,浏览器在处理、绘制、呈现内容和等待一些新的事件触发之间不断循环。事件触发器包括完成网络上资源的加载,例如,下载一个现在可以在屏幕上绘制的图像,完成由浏览器解析资源的过程,例如处理页面的HTML内容、用户与页面内容的交互,例如单击按钮。道格拉斯克罗克福德的几个讲座有效地解释了这种变化,特别是他说的,一个不方便的API:DOM的理论,解释了原来的浏览器流流量的变化

- -
A comparison of the sequential and event-driven browser load sequences.
- -

到事件驱动的浏览器。后一种方法将最后一个步骤从单个流变为一个永久循环,在接下来的步骤中,等待和处理新事件的发生。后一种方法的创新允许在资源尚未获得的情况下部分地呈现页面;该方法还允许使用JavaScript驱动的事件驱动操作。(可以从多个渠道获得,包括这一个)。目前,JavaScript代码的所有执行环境都使用事件和事件处理。

- -

事件设计模式

- -

事件系统的核心是简单的编程设计模式。模式从一个事件和一个事件的协议开始:

- -
    -
  • 事件使用的名称字符串,
  • -
  • 用于表示该事件的关键属性的数据结构的类型,以及
  • -
  • 将“发出”该事件的JavaScript对象。
  • -
- -

该模式的实现

- -
    -
  • 定义一个JavaScript函数,它作为一个参数,被商定的数据结构,以及
  • -
  • 使用将发出事件的对象使用名称字符串注册该函数。
  • -
- -

该功能称为“听众”或“与名称interchangibly处理”。这一模式可以很容易地使用完全自定义代码,如文章中关于自定义事件的说明所述。这种模式也被现代Web浏览器所使用,它定义了响应用户输入或浏览器活动而发出的许多事件。

- -

现代Web浏览器使用标准化方法跟踪事件模式。浏览器使用的数据结构对于事件的性质,从eventprototype对象派生对象。浏览器使用为功能,将处理这些数据结构的方法称为addEventListener期望作为参数的字符串类型的名称和事件处理函数的注册方法。最后,浏览器定义了大量的对象作为事件发射器,并定义了由对象生成的各种各样的事件类型。

- -

按钮的事件处理程序演示

- -

例如,浏览器按钮元素意在发出事件命名为'click'响应鼠标单击或当显示在触摸敏感表面,一个手指单击。我们可以在HTML页面中定义一个按钮:

- -
<button id="buttonOne">Click here to emit a 'click' event</button>
- -

而且,在JavaScript代码中,我们可以首先定义一个函数来监听“click”事件:

- -
var example_click_handler = function (ev){
-    var objKind = (ev instanceof Event) ? "EventPrototype" : "ObjectPrototype";
-    alert("We got a click event at " + ev.timeStamp + " with an argument object derived from: " + objKind );
-};
- -

第二,我们使用按钮对象注册我们的函数,无论是在脚本方面,还是使用HTML页面的DOM(文档对象模型)表示:

- -
var buttonDOMElement = document.querySelector('#buttonOne');
-buttonDOMElement.addEventListener('click', example_click_handler);
- -

或在HTML页面中添加功能的“onclick”属性的值,虽然这第二种方法通常只用于非常简单的网页。

- -

{{ EmbedLiveSample('Button_Event_Handler') }}

- -

这段代码依赖,有一种叫做“点击”事件,称任何监听协议(或处理)与一个事件对象参数的函数(实际上,在这种情况下,衍生的MouseEvent对象),将使用HTML按钮元素在用户交互。代码没有明显影响到用户的按钮,可以通过将鼠标指针放在HTML按钮,点击鼠标左键,或用手指或手写笔点上面的HTML按钮屏幕互动;当这种情况发生时,该buttonDOMElement  JavaScript对象会调用example_click_handler功能与事件对象作为参数。函数将依次执行程序员选择的任何操作,在这种情况下,打开一个HTML警报对话框。注意,处理程序对‘ev’对象有访问权,因为它作为参数传递;对象有关于事件的信息,特别是事件发生的时间。

- -

作为第二个例子,集成到Web页面中的许多现代JavaScript被封装到事件函数调用中,以确保代码只在HTML被处理并可用于更改或装饰时执行。例如,代码可以附加为:

- -
var funcInit = function(){
-    // user code goes here and can safetly address all the HTML elements from the page
-    // since the document has successfully been 'loaded'
-}
-document.addEventListener('DOMContentLoaded', funcInit);
-
-
- -

所以,此代码只会在文档对象发出“DOMContentLoaded“事件因为HTML解析完毕和javascript对象创建代表每个HTML文档的节点执行。注意,在这个例子中,代码甚至没有为函数命名事件参数,因为代码永远不需要使用描述事件的数据结构;相反,代码只需要等待运行,直到事件发生之后。

- -

因此,该模式易于学习和实现。事件的困难来自于学习在现代Web浏览器中生成的各种各样的事件。学习如何编写处理程序函数也有一些微妙之处,因为这些代码异步工作,可能会重复运行,但情况略有不同。

- -

值得注意的事件

- -

Web浏览器定义了大量事件,所以列出所有事件是不现实的。事件引用试图维护现代Web浏览器中使用的标准事件列表。

- -

一般来说,我们可以根据事件的对象来区分不同类型的事件,包括:

- -
    -
  • 窗口window对象,如由于调整浏览器大小,
  • -
  • window.screen对象,如由于设备的方向变化,
  • -
  • 文档document对象,包括页面的加载、修改、用户交互和卸载,
  • -
  • DOM(文档对象模型)树中的对象,包括用户交互或修改,
  • -
  • XMLHttpRequest对象用于网络的要求,和
  • -
  • 当媒体流播放器改变状态时,诸如音频audio和视频video等媒体对象。
  • -
- -

虽然这个列表目前不完整。

- -

一些值得注意的事件是:

- -
-

Note: 这份清单将需要相关的工作;这项工作正在等待一些关于文件的全球重组工作。这还需要找到在页面加载期间所涉及到的事件的良好解释,如部分讨论在  this web page 或 this Stack Overflow question.

-
- -
    -
  • 当页面完成渲染时,全局对象窗口window发出一个名为“load”的事件,这意味着所有资源都已下载并执行,以便运行脚本并显示图像,
  • -
  • 当浏览器窗口window的高度或宽度被用户更改时,全局对象窗口发出一个称为“resize”的事件,
  • -
  • DOM文档对象代表了HTML文件发出一个事件被称为”DOMContentLoaded“当文档加载完毕,
  • -
  • 当鼠标指针位于HTML页面的DOM节点顶部时,当用户按下鼠标按钮时,如div或button的DOM节点对象发出一个名为“click”的事件。
  • -
- -

事件对象层次结构

- -

Web浏览器定义了许多不同类型的事件。每个定义包括,作为数据结构传递给处理函数,一个对象继承自EventPrototype对象。

- -

事件对象类层次结构的部分图是:

- -
-

Note: 下面的图标是不完整的.

-
- -

- -

Web API文档包含定义事件对象的页面,该事件对象还包括事件对象已知的DOM事件子类。

- -

文档

- -

下面是三个链接对MDN(Mozilla开发者网络)网站程序员从事于事件相关的开发是特别有用的:

- - diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index 9e057c89e9..febfda2ca3 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -557,6 +557,7 @@ /zh-TW/docs/Web/API/Coordinates/latitude /zh-TW/docs/Web/API/GeolocationCoordinates/latitude /zh-TW/docs/Web/API/Coordinates/longitude /zh-TW/docs/Web/API/GeolocationCoordinates/longitude /zh-TW/docs/Web/API/Coordinates/speed /zh-TW/docs/Web/API/GeolocationCoordinates/speed +/zh-TW/docs/Web/API/Detecting_device_orientation /zh-TW/docs/orphaned/Web/API/Detecting_device_orientation /zh-TW/docs/Web/API/DocumentTemp /zh-TW/docs/Web/API/Document /zh-TW/docs/Web/API/DocumentTemp/createElement /zh-TW/docs/Web/API/Document/createElement /zh-TW/docs/Web/API/DocumentTemp/createRange /zh-TW/docs/Web/API/Document/createRange @@ -568,8 +569,9 @@ /zh-TW/docs/Web/API/DocumentTemp/querySelector /zh-TW/docs/Web/API/Document/querySelector /zh-TW/docs/Web/API/DocumentTemp/readyState /zh-TW/docs/Web/API/Document/readyState /zh-TW/docs/Web/API/DocumentTemp/width /zh-TW/docs/Web/API/Document/width +/zh-TW/docs/Web/API/Document_Object_Model/Events /zh-TW/docs/orphaned/Web/API/Document_Object_Model/Events /zh-TW/docs/Web/API/Document_Object_Model/Whitespace_in_the_DOM /zh-TW/docs/Web/API/Document_Object_Model/Whitespace -/zh-TW/docs/Web/API/Document_Object_Model/事件 /zh-TW/docs/Web/API/Document_Object_Model/Events +/zh-TW/docs/Web/API/Document_Object_Model/事件 /zh-TW/docs/orphaned/Web/API/Document_Object_Model/Events /zh-TW/docs/Web/API/Event/createEvent /zh-TW/docs/Web/API/Document/createEvent /zh-TW/docs/Web/API/Geolocation/Using_geolocation /zh-TW/docs/Web/API/Geolocation_API /zh-TW/docs/Web/API/HTMLElement/dataset /zh-TW/docs/Web/API/HTMLOrForeignElement/dataset @@ -644,7 +646,9 @@ /zh-TW/docs/Web/Guide/DOM /zh-TW/docs/conflicting/Web/API/Document_Object_Model /zh-TW/docs/Web/Guide/DOM/Manipulating_the_browser_history /zh-TW/docs/Web/API/History_API /zh-TW/docs/Web/Guide/DOM/Using_full_screen_mode /zh-TW/docs/Web/API/Fullscreen_API +/zh-TW/docs/Web/Guide/Events /zh-TW/docs/orphaned/Web/Guide/Events /zh-TW/docs/Web/Guide/Events/Creating_and_triggering_events /zh-TW/docs/orphaned/Web/Guide/Events/Creating_and_triggering_events +/zh-TW/docs/Web/Guide/Events/Event_handlers /zh-TW/docs/orphaned/Web/Guide/Events/Event_handlers /zh-TW/docs/Web/Guide/HTML /zh-TW/docs/Learn/HTML /zh-TW/docs/Web/Guide/HTML/Canvas_tutorial /zh-TW/docs/Web/API/Canvas_API/Tutorial /zh-TW/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors /zh-TW/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors @@ -832,7 +836,7 @@ /zh-TW/docs/Web/性能 /zh-TW/docs/Web/Performance /zh-TW/docs/WebAPI /zh-TW/docs/conflicting/Web/API /zh-TW/docs/WebAPI/Battery_Status /zh-TW/docs/Web/API/Battery_Status_API -/zh-TW/docs/WebAPI/Detecting_device_orientation /zh-TW/docs/Web/API/Detecting_device_orientation +/zh-TW/docs/WebAPI/Detecting_device_orientation /zh-TW/docs/orphaned/Web/API/Detecting_device_orientation /zh-TW/docs/WebAPI/FileHandle /zh-TW/docs/Web/API/File_Handle_API /zh-TW/docs/WebAPI/Managing_screen_orientation /zh-TW/docs/Web/API/CSS_Object_Model/Managing_screen_orientation /zh-TW/docs/WebAPI/Network_Information /zh-TW/docs/Web/API/Network_Information_API diff --git a/files/zh-tw/_wikihistory.json b/files/zh-tw/_wikihistory.json index e1c57a02d0..07a3ba24cc 100644 --- a/files/zh-tw/_wikihistory.json +++ b/files/zh-tw/_wikihistory.json @@ -3118,13 +3118,6 @@ "jackblackevo" ] }, - "Web/API/Detecting_device_orientation": { - "modified": "2019-03-23T23:27:03.486Z", - "contributors": [ - "jackblackevo", - "MashKao" - ] - }, "Web/API/DeviceMotionEvent": { "modified": "2019-03-23T22:19:09.256Z", "contributors": [ @@ -5284,20 +5277,6 @@ "shing0608" ] }, - "Web/Guide/Events": { - "modified": "2019-03-23T22:48:03.662Z", - "contributors": [ - "jackblackevo", - "gportioli" - ] - }, - "Web/Guide/Events/Event_handlers": { - "modified": "2020-05-13T00:05:39.122Z", - "contributors": [ - "ginszme", - "jackblackevo" - ] - }, "Web/Guide/Graphics": { "modified": "2019-04-23T04:21:07.806Z", "contributors": [ @@ -8082,12 +8061,6 @@ "Sonrisa" ] }, - "Web/API/Document_Object_Model/Events": { - "modified": "2019-03-23T22:27:33.501Z", - "contributors": [ - "H-W-Chang" - ] - }, "Web/API/Document/createTreeWalker": { "modified": "2019-03-23T23:14:12.386Z", "contributors": [ @@ -9152,5 +9125,32 @@ "jackblackevo", "Shiyou" ] + }, + "orphaned/Web/API/Detecting_device_orientation": { + "modified": "2019-03-23T23:27:03.486Z", + "contributors": [ + "jackblackevo", + "MashKao" + ] + }, + "orphaned/Web/API/Document_Object_Model/Events": { + "modified": "2019-03-23T22:27:33.501Z", + "contributors": [ + "H-W-Chang" + ] + }, + "orphaned/Web/Guide/Events/Event_handlers": { + "modified": "2020-05-13T00:05:39.122Z", + "contributors": [ + "ginszme", + "jackblackevo" + ] + }, + "orphaned/Web/Guide/Events": { + "modified": "2019-03-23T22:48:03.662Z", + "contributors": [ + "jackblackevo", + "gportioli" + ] } } \ No newline at end of file diff --git a/files/zh-tw/orphaned/web/api/detecting_device_orientation/index.html b/files/zh-tw/orphaned/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..20ff7fdf1e --- /dev/null +++ b/files/zh-tw/orphaned/web/api/detecting_device_orientation/index.html @@ -0,0 +1,279 @@ +--- +title: 偵測裝置方向 +slug: orphaned/Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +original_slug: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

目前支援 Web 的裝置,已有越來越多可偵測本身的方向(Orientation);也就是說,這些裝置可根據重力牽引的相對關係而改變其畫面方向,同時回報該筆資料。特別是如行動電話的手持式裝置,同樣會判斷這種資訊而自動旋轉其畫面。如此除了能保持正向畫面之外,裝置橫放時亦能以寬螢幕呈現網頁內容。

+ +

現有 2 組 JavaScript 事件可處理方向資訊。第一個是 {{domxref("DeviceOrientationEvent")}} 事件。只要加速規偵測到裝置方向的變化,隨即送出此事件。在接收並處理這些方向事件所回報的資料之後,即可針對使用者移動裝置所造成的方向與高度變化,確實做出回應。

+ +

第二個為 {{domxref("DeviceMotionEvent")}} 事件。只要加速過程產生變化,隨即送出該事件。此事件用以監聽加速過程的變化,因此不同於 {{domxref("DeviceOrientationEvent")}} 的方向變化。如筆記型電腦中的感測器,一般均能夠偵測 {{domxref("DeviceMotionEvent")}} 而保護移動中的儲存裝置。{{domxref("DeviceOrientationEvent")}} 則較常用於行動裝置。

+ +

處理方向事件

+ +

若要開始接收方向變換的情形,只要監聽 {{event("deviceorientation")}} 事件即可:

+ +
+

Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

在註冊了事件監聽器(Event listener。本範例使用 handleOrientation() 函式)之後,將以更新過的方向資料而定期呼叫你的監聽器函式。

+ +

方向事件共有 4 組值:

+ +
    +
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • +
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • +
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • +
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • +
+ +

事件處理器(Event handler)函式則如下列:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

方向值說明

+ +

所回報的各個軸線值,均是以標準座標而呈現對應各軸線的旋轉量 (Amount of rotation)。可參閱下方所提供的方向與動向資料說明文章以獲得詳細資訊。

+ +
    +
  • {{domxref("DeviceOrientationEvent.alpha")}} 值為裝置的 z 軸動向 (Motion),介於 0 ~ 360 度之間。
  • +
  • {{domxref("DeviceOrientationEvent.beta")}} 值為裝置的 x 軸動向,介於 -180 ~ 180 度之間,代表裝置的前後動向。
  • +
  • {{domxref("DeviceOrientationEvent.gamma")}} 值為裝置的 y 軸動向,介於 -90 ~ 90 度之間,代表裝置的左右動向。
  • +
+ +

方向範例

+ +

只要瀏覽器支援 {{event("deviceorientation")}} 事件,且該執行裝置可偵測自己的方向,均可使用此範例。

+ +

先想像花園裡有 1 顆球:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

這座花園為 200 像素寬(對,一座小花園),球就位在正中央:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

現在只要移動裝置,球也會跟著移動:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positioning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

這裡有即時結果 (若無法顯示,可至本文右上角切換回英文原文觀看):

+ +
{{EmbedLiveSample('Orientation_example', '230', '260')}}
+ +
+

警告:Chrome 與 Firefox 處理角度的方式不同,所以某些軸線可能方向顛倒。

+
+ +

處理動向事件

+ +

動向事件與方向事件的處理方式完全相同,但動向事件擁有自己的名稱:{{event("devicemotion")}}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

真正改變的是由 {{domxref("DeviceMotionEvent")}} 物件所提供的資訊;且該物件又作為 HandleMotion 函式的參數。

+ +

動向事件共有 4 組屬性:

+ +
    +
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • +
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • +
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • +
  • {{ domxref("DeviceMotionEvent.interval") }}
  • +
+ +

動向值說明

+ +

{{domxref("DeviceMotionEvent")}} 物件將提供「裝置位置與方向的變化速度」的相關資訊,並根據 3 組軸線 (可參閱方向與動向資料說明的細節) 提供變化情形。

+ +

針對 {{domxref("DeviceMotionEvent.acceleration","acceleration")}} 與 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}},這些軸線將對應:

+ +
    +
  • x:代表由東至西的軸線
  • +
  • y:代表由南至北的軸線
  • +
  • z:代表與地面垂直的軸線
  • +
+ +

針對稍有差異的 {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}},則資訊將對應:

+ +
    +
  • alpha:代表與螢幕 (或桌機的鍵盤) 垂直的軸線之旋轉率
  • +
  • beta:代表與螢幕平面 (或桌機的鍵盤) 由左至右軸線之旋轉率
  • +
  • gamma:代表與螢幕平面 (或桌機的鍵盤) 由下至上軸線之旋轉率
  • +
+ +

最後,{{domxref("DeviceMotionEvent.interval","interval")}} 代表以毫秒(Millisecond)為單位的時間間隔,是裝置取得資料的頻率。

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.0{{CompatVersionUnknown}}3.6[1]
+ 6
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.0{{CompatVersionUnknown}}3.6[1]
+ 6
{{CompatNo}}{{CompatNo}}4.2
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Firefox 3.6 to 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event.

+ +

參見

+ + diff --git a/files/zh-tw/orphaned/web/api/document_object_model/events/index.html b/files/zh-tw/orphaned/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..46004806f0 --- /dev/null +++ b/files/zh-tw/orphaned/web/api/document_object_model/events/index.html @@ -0,0 +1,70 @@ +--- +title: 事件與DOM +slug: orphaned/Web/API/Document_Object_Model/Events +translation_of: Web/API/Document_Object_Model/Events +original_slug: Web/API/Document_Object_Model/Events +--- +

Introduction

+ +

This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Registering event listeners

+ +

There are 3 ways to register event handlers for a DOM element.

+ +

EventTarget.addEventListener

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

This is the method you should use in modern web pages.

+ +

Note: Internet Explorer 6-8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility use one of the many JavaScript libraries available.

+ +

More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.

+ +

HTML attribute

+ +
<button onclick="alert('Hello world!')">
+
+ +

The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

+ +

DOM element properties

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects including DOM elements, document, the window object, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
function foo(evt) {
+  // the evt parameter is automatically assigned the event object
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/zh-tw/orphaned/web/guide/events/event_handlers/index.html b/files/zh-tw/orphaned/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..b586069c13 --- /dev/null +++ b/files/zh-tw/orphaned/web/guide/events/event_handlers/index.html @@ -0,0 +1,179 @@ +--- +title: DOM on-event 處理器 +slug: orphaned/Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +original_slug: Web/Guide/Events/Event_handlers +--- +

Web 平台提供了多種獲得 DOM 事件通知的方式。兩種常見的風格為:通用的 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 及一組特定的 on-event 處理器。本頁聚焦在後者如何運作的細節。

+ +

註冊 on-event 處理器

+ +

on-event 處理器為一群由 DOM 元素提供的屬性({{Glossary("property")}}),用來協助管理元素要如何應對事件。元素可以是具互動性的(如:links、buttons、images、forms)或非互動性的(如頁面基礎 document)。事件為一個操作,像是點擊(clicked)、偵測按下按鍵(pressed keys)、取得焦點(focus)等。on-event 處理器通常是根據它被設計來應對的事件,例如 onclickonkeypressonfocus 等等。

+ +

你可以使用兩種不同的方式來為一個物件的特定事件(例如:{{event("click")}})指定一個 on<...> 事件處理器:

+ +
    +
  • 在元素上使用一個名稱為 on{eventtype} 的 HTML 標籤屬性({{Glossary("attribute")}}),例如:
    + <button onclick="return handleClick(event);">,
  • +
  • 或藉由設定相對應的 JavaScript 屬性({{Glossary("property/JavaScript", "property")}}),例如:
    + document.getElementById("mybutton").onclick = function(event) { ... }.
  • +
+ +

Note that each object can have only one on-event handler for a given event (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

+ +

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

+ +

非元素物件

+ +

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

+ +
xhr.onprogress = function() { ... }
+ +

細節

+ +

HTML 的 on<...> 屬性值及對應的 JavaScript 屬性

+ +

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

+ +
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
+
+<script>
+window.onload = function () {
+  var div = document.getElementById("a");
+  console.log("Attribute reflected as a property: ", div.onclick.toString());
+  // Prints: function onclick(event) { alert('old') }
+  div.onclick = function() { alert('new') };
+  console.log("Changed property to: ", div.onclick.toString());
+  // Prints: function () { alert('new') }
+  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
+  // Prints: alert('old')
+}
+</script>
+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

+ +

事件處理器的參數、this 綁定及回傳值

+ +

當一個事件處理被定義成為一個 HTML 的屬性時,給定的程式碼會被包成一個具有下列參數的函式:

+ +
    +
  • event - 除了{{domxref("GlobalEventHandlers.onerror", "onerror")}}的事件以外,其他所有的事件都會有此參數。
  • +
  • event, source, lineno, colno, 還有專為 {{domxref("GlobalEventHandlers.onerror", "onerror")}} 事件處理的 error 。請注意: event 參數實際上擁有以字串形式呈現的錯誤訊息。
  • +
+ +

當事件處理函式被觸發時,處理函式中的關鍵字: this 被設定成為註冊這個事件處理函式的DOM 元件。 請參閱 this 關鍵字說明 獲得更多細節。

+ +

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event, for details see "The event handler processing algorithm" in the HTML specification.

+ +

當事件處理器被調用

+ +

TBD (non-capturing listener)

+ +

術語

+ +

The term event handler may be used to refer to:

+ +
    +
  • any function or object registered to be notified of events,
  • +
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • +
+ +

When discussing the various methods of listening to events,

+ +
    +
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • +
  • whereas event handler refers to a function registered via on... attributes or properties.
  • +
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Event handler changes in Firefox 9

+ +

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

+ +

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

+ +

Detecting the presence of event handler properties

+ +

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

You can't set or access the values of any IDL-defined attributes on DOM prototype objects; that means you can't, for example, change Window.prototype.onload anymore. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/zh-tw/orphaned/web/guide/events/index.html b/files/zh-tw/orphaned/web/guide/events/index.html new file mode 100644 index 0000000000..1907f58bd1 --- /dev/null +++ b/files/zh-tw/orphaned/web/guide/events/index.html @@ -0,0 +1,53 @@ +--- +title: Event developer guide +slug: orphaned/Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub +translation_of: Web/Guide/Events +original_slug: Web/Guide/Events +--- +

{{draft()}}

+ +

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+ +

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+ +

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation.

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

文件

+ +

{{LandingPageListSubpages}}

diff --git a/files/zh-tw/web/api/detecting_device_orientation/index.html b/files/zh-tw/web/api/detecting_device_orientation/index.html deleted file mode 100644 index d81307ba57..0000000000 --- a/files/zh-tw/web/api/detecting_device_orientation/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: 偵測裝置方向 -slug: Web/API/Detecting_device_orientation -translation_of: Web/API/Detecting_device_orientation ---- -
{{SeeCompatTable}}
- -

目前支援 Web 的裝置,已有越來越多可偵測本身的方向(Orientation);也就是說,這些裝置可根據重力牽引的相對關係而改變其畫面方向,同時回報該筆資料。特別是如行動電話的手持式裝置,同樣會判斷這種資訊而自動旋轉其畫面。如此除了能保持正向畫面之外,裝置橫放時亦能以寬螢幕呈現網頁內容。

- -

現有 2 組 JavaScript 事件可處理方向資訊。第一個是 {{domxref("DeviceOrientationEvent")}} 事件。只要加速規偵測到裝置方向的變化,隨即送出此事件。在接收並處理這些方向事件所回報的資料之後,即可針對使用者移動裝置所造成的方向與高度變化,確實做出回應。

- -

第二個為 {{domxref("DeviceMotionEvent")}} 事件。只要加速過程產生變化,隨即送出該事件。此事件用以監聽加速過程的變化,因此不同於 {{domxref("DeviceOrientationEvent")}} 的方向變化。如筆記型電腦中的感測器,一般均能夠偵測 {{domxref("DeviceMotionEvent")}} 而保護移動中的儲存裝置。{{domxref("DeviceOrientationEvent")}} 則較常用於行動裝置。

- -

處理方向事件

- -

若要開始接收方向變換的情形,只要監聽 {{event("deviceorientation")}} 事件即可:

- -
-

Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

-
- -
window.addEventListener("deviceorientation", handleOrientation, true);
-
- -

在註冊了事件監聽器(Event listener。本範例使用 handleOrientation() 函式)之後,將以更新過的方向資料而定期呼叫你的監聽器函式。

- -

方向事件共有 4 組值:

- -
    -
  • {{ domxref("DeviceOrientationEvent.absolute") }}
  • -
  • {{ domxref("DeviceOrientationEvent.alpha") }}
  • -
  • {{ domxref("DeviceOrientationEvent.beta") }}
  • -
  • {{ domxref("DeviceOrientationEvent.gamma") }}
  • -
- -

事件處理器(Event handler)函式則如下列:

- -
function handleOrientation(event) {
-  var absolute = event.absolute;
-  var alpha    = event.alpha;
-  var beta     = event.beta;
-  var gamma    = event.gamma;
-
-  // Do stuff with the new orientation data
-}
-
- -

方向值說明

- -

所回報的各個軸線值,均是以標準座標而呈現對應各軸線的旋轉量 (Amount of rotation)。可參閱下方所提供的方向與動向資料說明文章以獲得詳細資訊。

- -
    -
  • {{domxref("DeviceOrientationEvent.alpha")}} 值為裝置的 z 軸動向 (Motion),介於 0 ~ 360 度之間。
  • -
  • {{domxref("DeviceOrientationEvent.beta")}} 值為裝置的 x 軸動向,介於 -180 ~ 180 度之間,代表裝置的前後動向。
  • -
  • {{domxref("DeviceOrientationEvent.gamma")}} 值為裝置的 y 軸動向,介於 -90 ~ 90 度之間,代表裝置的左右動向。
  • -
- -

方向範例

- -

只要瀏覽器支援 {{event("deviceorientation")}} 事件,且該執行裝置可偵測自己的方向,均可使用此範例。

- -

先想像花園裡有 1 顆球:

- -
<div class="garden">
-  <div class="ball"></div>
-</div>
-
-<pre class="output"></pre>
-
- -

這座花園為 200 像素寬(對,一座小花園),球就位在正中央:

- -
.garden {
-  position: relative;
-  width : 200px;
-  height: 200px;
-  border: 5px solid #CCC;
-  border-radius: 10px;
-}
-
-.ball {
-  position: absolute;
-  top   : 90px;
-  left  : 90px;
-  width : 20px;
-  height: 20px;
-  background: green;
-  border-radius: 100%;
-}
-
- -

現在只要移動裝置,球也會跟著移動:

- -
var ball   = document.querySelector('.ball');
-var garden = document.querySelector('.garden');
-var output = document.querySelector('.output');
-
-var maxX = garden.clientWidth  - ball.clientWidth;
-var maxY = garden.clientHeight - ball.clientHeight;
-
-function handleOrientation(event) {
-  var x = event.beta;  // In degree in the range [-180,180]
-  var y = event.gamma; // In degree in the range [-90,90]
-
-  output.innerHTML  = "beta : " + x + "\n";
-  output.innerHTML += "gamma: " + y + "\n";
-
-  // Because we don't want to have the device upside down
-  // We constrain the x value to the range [-90,90]
-  if (x >  90) { x =  90};
-  if (x < -90) { x = -90};
-
-  // To make computation easier we shift the range of
-  // x and y to [0,180]
-  x += 90;
-  y += 90;
-
-  // 10 is half the size of the ball
-  // It center the positioning point to the center of the ball
-  ball.style.top  = (maxX*x/180 - 10) + "px";
-  ball.style.left = (maxY*y/180 - 10) + "px";
-}
-
-window.addEventListener('deviceorientation', handleOrientation);
-
- -

這裡有即時結果 (若無法顯示,可至本文右上角切換回英文原文觀看):

- -
{{EmbedLiveSample('Orientation_example', '230', '260')}}
- -
-

警告:Chrome 與 Firefox 處理角度的方式不同,所以某些軸線可能方向顛倒。

-
- -

處理動向事件

- -

動向事件與方向事件的處理方式完全相同,但動向事件擁有自己的名稱:{{event("devicemotion")}}

- -
window.addEventListener("devicemotion", handleMotion, true);
- -

真正改變的是由 {{domxref("DeviceMotionEvent")}} 物件所提供的資訊;且該物件又作為 HandleMotion 函式的參數。

- -

動向事件共有 4 組屬性:

- -
    -
  • {{ domxref("DeviceMotionEvent.acceleration") }}
  • -
  • {{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}
  • -
  • {{ domxref("DeviceMotionEvent.rotationRate") }}
  • -
  • {{ domxref("DeviceMotionEvent.interval") }}
  • -
- -

動向值說明

- -

{{domxref("DeviceMotionEvent")}} 物件將提供「裝置位置與方向的變化速度」的相關資訊,並根據 3 組軸線 (可參閱方向與動向資料說明的細節) 提供變化情形。

- -

針對 {{domxref("DeviceMotionEvent.acceleration","acceleration")}} 與 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}},這些軸線將對應:

- -
    -
  • x:代表由東至西的軸線
  • -
  • y:代表由南至北的軸線
  • -
  • z:代表與地面垂直的軸線
  • -
- -

針對稍有差異的 {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}},則資訊將對應:

- -
    -
  • alpha:代表與螢幕 (或桌機的鍵盤) 垂直的軸線之旋轉率
  • -
  • beta:代表與螢幕平面 (或桌機的鍵盤) 由左至右軸線之旋轉率
  • -
  • gamma:代表與螢幕平面 (或桌機的鍵盤) 由下至上軸線之旋轉率
  • -
- -

最後,{{domxref("DeviceMotionEvent.interval","interval")}} 代表以毫秒(Millisecond)為單位的時間間隔,是裝置取得資料的頻率。

- -

規範

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
- -

瀏覽器相容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.0{{CompatVersionUnknown}}3.6[1]
- 6
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.0{{CompatVersionUnknown}}3.6[1]
- 6
{{CompatNo}}{{CompatNo}}4.2
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Firefox 3.6 to 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event.

- -

參見

- - diff --git a/files/zh-tw/web/api/document_object_model/events/index.html b/files/zh-tw/web/api/document_object_model/events/index.html deleted file mode 100644 index 7949e5506a..0000000000 --- a/files/zh-tw/web/api/document_object_model/events/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 事件與DOM -slug: Web/API/Document_Object_Model/Events -translation_of: Web/API/Document_Object_Model/Events -original_slug: Web/API/Document_Object_Model/事件 ---- -

Introduction

- -

This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.

- -

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

- -

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

- -

Registering event listeners

- -

There are 3 ways to register event handlers for a DOM element.

- -

EventTarget.addEventListener

- -
// Assuming myButton is a button element
-myButton.addEventListener('click', function(){alert('Hello world');}, false);
-
- -

This is the method you should use in modern web pages.

- -

Note: Internet Explorer 6-8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility use one of the many JavaScript libraries available.

- -

More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.

- -

HTML attribute

- -
<button onclick="alert('Hello world!')">
-
- -

The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification.

- -

This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

- -

DOM element properties

- -
// Assuming myButton is a button element
-myButton.onclick = function(event){alert('Hello world');};
-
- -

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

- -

The problem with this method is that only one handler can be set per element and per event.

- -

Accessing Event interfaces

- -

Event handlers may be attached to various objects including DOM elements, document, the window object, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.

- -

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

- -
function foo(evt) {
-  // the evt parameter is automatically assigned the event object
-  alert(evt);
-}
-table_el.onclick = foo;
-
- - - - diff --git a/files/zh-tw/web/guide/events/event_handlers/index.html b/files/zh-tw/web/guide/events/event_handlers/index.html deleted file mode 100644 index 519ac8bf90..0000000000 --- a/files/zh-tw/web/guide/events/event_handlers/index.html +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: DOM on-event 處理器 -slug: Web/Guide/Events/Event_handlers -translation_of: Web/Guide/Events/Event_handlers ---- -

Web 平台提供了多種獲得 DOM 事件通知的方式。兩種常見的風格為:通用的 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 及一組特定的 on-event 處理器。本頁聚焦在後者如何運作的細節。

- -

註冊 on-event 處理器

- -

on-event 處理器為一群由 DOM 元素提供的屬性({{Glossary("property")}}),用來協助管理元素要如何應對事件。元素可以是具互動性的(如:links、buttons、images、forms)或非互動性的(如頁面基礎 document)。事件為一個操作,像是點擊(clicked)、偵測按下按鍵(pressed keys)、取得焦點(focus)等。on-event 處理器通常是根據它被設計來應對的事件,例如 onclickonkeypressonfocus 等等。

- -

你可以使用兩種不同的方式來為一個物件的特定事件(例如:{{event("click")}})指定一個 on<...> 事件處理器:

- -
    -
  • 在元素上使用一個名稱為 on{eventtype} 的 HTML 標籤屬性({{Glossary("attribute")}}),例如:
    - <button onclick="return handleClick(event);">,
  • -
  • 或藉由設定相對應的 JavaScript 屬性({{Glossary("property/JavaScript", "property")}}),例如:
    - document.getElementById("mybutton").onclick = function(event) { ... }.
  • -
- -

Note that each object can have only one on-event handler for a given event (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

- -

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

- -

非元素物件

- -

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

- -
xhr.onprogress = function() { ... }
- -

細節

- -

HTML 的 on<...> 屬性值及對應的 JavaScript 屬性

- -

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

- -
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
-
-<script>
-window.onload = function () {
-  var div = document.getElementById("a");
-  console.log("Attribute reflected as a property: ", div.onclick.toString());
-  // Prints: function onclick(event) { alert('old') }
-  div.onclick = function() { alert('new') };
-  console.log("Changed property to: ", div.onclick.toString());
-  // Prints: function () { alert('new') }
-  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
-  // Prints: alert('old')
-}
-</script>
- -

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

- -

事件處理器的參數、this 綁定及回傳值

- -

當一個事件處理被定義成為一個 HTML 的屬性時,給定的程式碼會被包成一個具有下列參數的函式:

- -
    -
  • event - 除了{{domxref("GlobalEventHandlers.onerror", "onerror")}}的事件以外,其他所有的事件都會有此參數。
  • -
  • event, source, lineno, colno, 還有專為 {{domxref("GlobalEventHandlers.onerror", "onerror")}} 事件處理的 error 。請注意: event 參數實際上擁有以字串形式呈現的錯誤訊息。
  • -
- -

當事件處理函式被觸發時,處理函式中的關鍵字: this 被設定成為註冊這個事件處理函式的DOM 元件。 請參閱 this 關鍵字說明 獲得更多細節。

- -

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event, for details see "The event handler processing algorithm" in the HTML specification.

- -

當事件處理器被調用

- -

TBD (non-capturing listener)

- -

術語

- -

The term event handler may be used to refer to:

- -
    -
  • any function or object registered to be notified of events,
  • -
  • or, more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in web APIs, such as <button onclick="alert(this)"> or window.onload = function() { /* ... */ }.
  • -
- -

When discussing the various methods of listening to events,

- -
    -
  • event listener refers to a function or object registered via {{domxref("EventTarget.addEventListener()")}},
  • -
  • whereas event handler refers to a function registered via on... attributes or properties.
  • -
- -

規範

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
- -

瀏覽器相容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Event handler changes in Firefox 9

- -

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

- -

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

- -

Detecting the presence of event handler properties

- -

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

- -
if ("onsomenewfeature" in window) {
-  /* do something amazing */
-}
-
- -

Event handlers and prototypes

- -

You can't set or access the values of any IDL-defined attributes on DOM prototype objects; that means you can't, for example, change Window.prototype.onload anymore. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/zh-tw/web/guide/events/index.html b/files/zh-tw/web/guide/events/index.html deleted file mode 100644 index 4484986b66..0000000000 --- a/files/zh-tw/web/guide/events/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Event developer guide -slug: Web/Guide/Events -tags: - - DOM - - Event - - Guide - - NeedsTranslation - - NeedsUpdate - - TopicStub -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation.

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

文件

- -

{{LandingPageListSubpages}}

-- cgit v1.2.3-54-g00ecf