From 43a5cac2eff22c21071800e13bef12af9d3a37d0 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 13:12:08 +0100 Subject: unslug zh-tw: move --- .../drawing_graphics_with_canvas/index.html | 162 ----- files/zh-tw/web/api/closeevent/index.html | 145 +++++ .../web/api/document.createtreewalker/index.html | 224 ------- .../zh-tw/web/api/document/createevent/index.html | 30 + .../web/api/document/createtreewalker/index.html | 224 +++++++ .../api/document_object_model/events/index.html | 69 ++ .../\344\272\213\344\273\266/index.html" | 69 -- .../web/api/elementcssinlinestyle/style/index.html | 79 +++ files/zh-tw/web/api/event/createevent/index.html | 30 - .../api/geolocation/using_geolocation/index.html | 251 -------- files/zh-tw/web/api/geolocation_api/index.html | 251 ++++++++ files/zh-tw/web/api/htmlelement/dataset/index.html | 167 ----- .../zh-tw/web/api/htmlelement/innertext/index.html | 86 +++ files/zh-tw/web/api/htmlelement/style/index.html | 79 --- .../api/htmlmediaelement/abort_event/index.html | 68 ++ .../api/htmlorforeignelement/dataset/index.html | 167 +++++ files/zh-tw/web/api/messageevent/index.html | 80 +++ files/zh-tw/web/api/node/innertext/index.html | 86 --- files/zh-tw/web/api/performance.timing/index.html | 56 -- files/zh-tw/web/api/performance/timing/index.html | 56 ++ files/zh-tw/web/api/permissions_api/index.html | 85 +++ .../api/web_video_text_tracks_format/index.html | 691 --------------------- files/zh-tw/web/api/websocket/index.html | 276 ++++++++ files/zh-tw/web/api/websockets_api/index.html | 155 +++++ .../index.html | 179 ++++++ files/zh-tw/web/api/webvtt_api/index.html | 691 +++++++++++++++++++++ files/zh-tw/web/api/window.history/index.html | 51 -- files/zh-tw/web/api/window.onpopstate/index.html | 57 -- .../api/window.requestanimationframe/index.html | 94 --- .../api/window/domcontentloaded_event/index.html | 133 ++++ files/zh-tw/web/api/window/history/index.html | 51 ++ files/zh-tw/web/api/window/load_event/index.html | 88 +++ .../api/window/requestanimationframe/index.html | 94 +++ .../index.html | 36 -- files/zh-tw/web/api/windowbase64/index.html | 114 ---- .../api/windoweventhandlers/onpopstate/index.html | 57 ++ files/zh-tw/web/api/windowtimers/index.html | 115 ---- 37 files changed, 3064 insertions(+), 2282 deletions(-) delete mode 100644 files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html create mode 100644 files/zh-tw/web/api/closeevent/index.html delete mode 100644 files/zh-tw/web/api/document.createtreewalker/index.html create mode 100644 files/zh-tw/web/api/document/createevent/index.html create mode 100644 files/zh-tw/web/api/document/createtreewalker/index.html create mode 100644 files/zh-tw/web/api/document_object_model/events/index.html delete mode 100644 "files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" create mode 100644 files/zh-tw/web/api/elementcssinlinestyle/style/index.html delete mode 100644 files/zh-tw/web/api/event/createevent/index.html delete mode 100644 files/zh-tw/web/api/geolocation/using_geolocation/index.html create mode 100644 files/zh-tw/web/api/geolocation_api/index.html delete mode 100644 files/zh-tw/web/api/htmlelement/dataset/index.html create mode 100644 files/zh-tw/web/api/htmlelement/innertext/index.html delete mode 100644 files/zh-tw/web/api/htmlelement/style/index.html create mode 100644 files/zh-tw/web/api/htmlmediaelement/abort_event/index.html create mode 100644 files/zh-tw/web/api/htmlorforeignelement/dataset/index.html create mode 100644 files/zh-tw/web/api/messageevent/index.html delete mode 100644 files/zh-tw/web/api/node/innertext/index.html delete mode 100644 files/zh-tw/web/api/performance.timing/index.html create mode 100644 files/zh-tw/web/api/performance/timing/index.html create mode 100644 files/zh-tw/web/api/permissions_api/index.html delete mode 100644 files/zh-tw/web/api/web_video_text_tracks_format/index.html create mode 100644 files/zh-tw/web/api/websocket/index.html create mode 100644 files/zh-tw/web/api/websockets_api/index.html create mode 100644 files/zh-tw/web/api/websockets_api/writing_websocket_client_applications/index.html create mode 100644 files/zh-tw/web/api/webvtt_api/index.html delete mode 100644 files/zh-tw/web/api/window.history/index.html delete mode 100644 files/zh-tw/web/api/window.onpopstate/index.html delete mode 100644 files/zh-tw/web/api/window.requestanimationframe/index.html create mode 100644 files/zh-tw/web/api/window/domcontentloaded_event/index.html create mode 100644 files/zh-tw/web/api/window/history/index.html create mode 100644 files/zh-tw/web/api/window/load_event/index.html create mode 100644 files/zh-tw/web/api/window/requestanimationframe/index.html delete mode 100644 files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html delete mode 100644 files/zh-tw/web/api/windowbase64/index.html create mode 100644 files/zh-tw/web/api/windoweventhandlers/onpopstate/index.html delete mode 100644 files/zh-tw/web/api/windowtimers/index.html (limited to 'files/zh-tw/web/api') diff --git a/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html b/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html deleted file mode 100644 index 63bd0017fc..0000000000 --- a/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Drawing graphics with canvas -slug: Web/API/Canvas_API/Drawing_graphics_with_canvas -translation_of: Web/API/Canvas_API/Tutorial -translation_of_original: Web/API/Canvas_API/Drawing_graphics_with_canvas ---- -
-

Most of this content (but not the documentation on drawWindow) has been rolled into the more expansive Canvas tutorial, this page should probably be redirected there as it's now redundant but some information may still be relevant.

-
-

介紹

-

  在 Firefox 1.5, Firefox 引入了新的 HTML 元素 <canvas> 來繪製圖形。<canvas> 是基於 WHATWG canvas specification 的技術 (其發軔於蘋果公司在 Safari 上的實做)。 我們可以用它來在使用者端進行圖形和 UI 元件的渲染。

-

  <canvas> 創建了一個具有一致多個 rendering contexts 的區域。在本文中,我們著重於 2D rendering context 的部份。對於 3D 圖形,您可以參考 WebGL rendering context

-

2D Rendering Context

-

先來個簡單的範例

-

  以下的程式碼做了一個簡單的展示:繪製兩個部份交疊的矩形 (其中一個矩形有透明屬性) :

-
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  ctx.fillStyle = "rgb(200,0,0)";
-  ctx.fillRect (10, 10, 55, 50);
-
-  ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
-  ctx.fillRect (30, 30, 55, 50);
-}
-
- -

{{EmbedLiveSample('A_Simple_Example','150','150','/@api/deki/files/602/=Canvas_ex1.png')}}

-

  這個名為 draw 的函式從 canvas element 取得 2d context。物件 ctx 可以被用來在 canvas 上頭繪製圖形。從程式碼可以看出,我們簡單的藉由設定 fillStyle 繪製了兩個顏色不同的矩形,並透過 fillRect 設定其位置。此外,第二個矩形透過 rgba() 配置了透明屬性。

-

  關於更複雜的圖形繪製,我們可以使用 fillRect, strokeRect 和 clearRect,他們分別可以畫出填滿的矩形, 僅有外框的矩形以及矩形區域清除。

-

路徑的使用

-

  beginPath 函式用來初始一段路徑的繪製,並且可以透過 moveTo, lineTo, arcTo, arc 以及相關的函式來描述路徑內容。要結束的時候呼叫 closePath 即可。一旦路徑描述完畢,就可以透過 fill 或 stroke 來渲染該路徑在 canvas 上。

-
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  ctx.fillStyle = "red";
-
-  ctx.beginPath();
-  ctx.moveTo(30, 30);
-  ctx.lineTo(150, 150);
-  // was: ctx.quadraticCurveTo(60, 70, 70, 150); which is wrong.
-  ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- this is right formula for the image on the right ->
-  ctx.lineTo(30, 30);
-  ctx.fill();
-}
-
- -

{{EmbedLiveSample('Using_Paths','190','190','/@api/deki/files/603/=Canvas_ex2.png')}}

-

  呼叫 fill() 或 stroke() 代表該路徑已經被使用。若要重新進行填滿等動作,則需要重頭創造一次路徑。

-

圖像狀態

-

  fillStyle, strokeStyle, lineWidth 和 lineJoin 等屬性是 graphics state 的一部分。關於這些屬性的修改,您可以透過 save() 及 restore() 來進行操作。

-

一個更為複雜的範例

-

  接著我們來看一個稍微複雜一點的範例,它同時引入了路徑, 狀態的修改以及變換矩陣。

-
function drawBowtie(ctx, fillStyle) {
-
-  ctx.fillStyle = "rgba(200,200,200,0.3)";
-  ctx.fillRect(-30, -30, 60, 60);
-
-  ctx.fillStyle = fillStyle;
-  ctx.globalAlpha = 1.0;
-  ctx.beginPath();
-  ctx.moveTo(25, 25);
-  ctx.lineTo(-25, -25);
-  ctx.lineTo(25, -25);
-  ctx.lineTo(-25, 25);
-  ctx.closePath();
-  ctx.fill();
-}
-
-function dot(ctx) {
-  ctx.save();
-  ctx.fillStyle = "black";
-  ctx.fillRect(-2, -2, 4, 4);
-  ctx.restore();
-}
-
-function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // note that all other translates are relative to this one
-  ctx.translate(45, 45);
-
-  ctx.save();
-  //ctx.translate(0, 0); // unnecessary
-  drawBowtie(ctx, "red");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(85, 0);
-  ctx.rotate(45 * Math.PI / 180);
-  drawBowtie(ctx, "green");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(0, 85);
-  ctx.rotate(135 * Math.PI / 180);
-  drawBowtie(ctx, "blue");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(85, 85);
-  ctx.rotate(90 * Math.PI / 180);
-  drawBowtie(ctx, "yellow");
-  dot(ctx);
-  ctx.restore();
-}
-
- -

{{EmbedLiveSample('A_More_Complicated_Example','215','215','/@api/deki/files/604/=Canvas_ex3.png')}}

-

  我們自定義了兩個函式: drawBowtie 以及 dot,並且個別呼叫了四次。在呼叫他們之前,我們使用了 translate()rotate() 來設定接著要繪製圖形的 transformation matrix,這將改變最終 dot 和 bowtie 的位置。dot 繪製了一個以 (0, 0) 為中心的小黑正方形,而 drawBowtie 產生了一個填滿的蝴蝶結樣貌的圖形。

-

  save() 和 restore() 規範了一系列動作的初始和結尾。一個值得注意的地方是,旋轉的動作是基於該圖形當下所在的位置, 所以 translate() -> rotate() -> translate() 的結果會和 translate() -> translate() -> rotate() 不同。

-

和 Apple <canvas> 的相容性

-

For the most part, <canvas> is compatible with Apple's and other implementations. There are, however, a few issues to be aware of, described here.

-

</canvas> tag 是必要的

-

In the Apple Safari implementation, <canvas> is an element implemented in much the same way <img> is; it does not have an end tag. However, for <canvas> to have widespread use on the web, some facility for fallback content must be provided. Therefore, Mozilla's implementation has a required end tag.

-

If fallback content is not needed, a simple <canvas id="foo" ...></canvas> will be fully compatible with both Safari and Mozilla -- Safari will simply ignore the end tag.

-

If fallback content is desired, some CSS tricks must be employed to mask the fallback content from Safari (which should render just the canvas), and also to mask the CSS tricks themselves from IE (which should render the fallback content).

-
canvas {
-  font-size: 0.00001px !ie;
-}
-

其他特性

-

藉由 Canvas 渲染網頁內容

-
- This feature is only available for code running with Chrome privileges. It is not allowed in normal HTML pages. Read why.
-

Mozilla's canvas is extended with the drawWindow() method. This method draws a snapshot of the contents of a DOM window into the canvas. For example,

-
ctx.drawWindow(window, 0, 0, 100, 200, "rgb(255,255,255)");
-
-

would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white background, into the canvas. By specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with a transparent background (which would be slower).

-

It is usually a bad idea to use any background other than pure white "rgb(255,255,255)" or transparent, as this is what all browsers do, and many websites expect that transparent parts of their interface will be drawn on white background.

-

With this method, it is possible to fill a hidden IFRAME with arbitrary content (e.g., CSS-styled HTML text, or SVG) and draw it into a canvas. It will be scaled, rotated and so on according to the current transformation.

-

Ted Mielczarek's tab preview extension uses this technique in chrome to provide thumbnails of web pages, and the source is available for reference.

-
- Note: Using canvas.drawWindow() while handling a document's onload event doesn't work. In Firefox 3.5 or later, you can do this in a handler for the MozAfterPaint event to successfully draw HTML content into a canvas on page load.
-

更多資訊

- diff --git a/files/zh-tw/web/api/closeevent/index.html b/files/zh-tw/web/api/closeevent/index.html new file mode 100644 index 0000000000..0a6d0977ff --- /dev/null +++ b/files/zh-tw/web/api/closeevent/index.html @@ -0,0 +1,145 @@ +--- +title: CloseEvent +slug: WebSockets/WebSockets_reference/CloseEvent +tags: + - WebSockets +translation_of: Web/API/CloseEvent +--- +

{{ draft() }}

+

當 WebSocket 連線關閉時,客戶端會收到一個 CloseEvent,由 WebSocket 物件 onclose 屬性表示的監聽器接收。

+

屬性

+ + + + + + + + + + + + + + + + + + + + + + + +
屬性形態描述
codeunsigned longWebSocket 伺服器給予的連線關閉代碼。「狀態代碼」列有所有可能值。
reason{{ domxref("DOMString") }}表示伺服器關閉連線的原因,這因不同的伺服器與子協定而定。
wasCleanboolean表示連線關閉情況是否乾淨。
+

狀態代碼

+

以下列有所有合法的狀態代碼。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
狀態代碼描述
0-999尚未使用的保留值。
1000正常關閉,連線成功地達到建立時的目標。
1001端點去離,伺服器故障或是瀏覽器從開啟連線的頁面離去的情形。
1002因協定錯誤造成連線被端點消滅。
1003因端點接收不能處理的資料形態(舉例來說,文字端點收到二進制資料)而消滅連線。
1004端點收到過大的資料幀而消滅連線。
1005保留值。表示意外地未給予狀態代碼的情形。
1006保留值。用以表示在預期收到狀態代碼的情形下不正常(即未送關閉幀)的連線關閉。
1007-1999保留以作為未來的 WebSocket 標準之用。
2000-2999保留以作為 WebSocket 擴展之用。
3000-3999程式庫與框架使用的值,應用程式可不使用。
4000-4999應用程式使用的值。
+

參見

+ +

瀏覽器兼容

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

Gecko 備註

+

此時此刻,Gecko 送至監聽器的 "close" 事件僅是簡單事件。

+

{{ languages ( {"en": "en/WebSockets/WebSockets_reference/CloseEvent"} ) }}

diff --git a/files/zh-tw/web/api/document.createtreewalker/index.html b/files/zh-tw/web/api/document.createtreewalker/index.html deleted file mode 100644 index 9e74411a14..0000000000 --- a/files/zh-tw/web/api/document.createtreewalker/index.html +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Document.createTreeWalker() -slug: Web/API/document.createTreeWalker -translation_of: Web/API/Document/createTreeWalker ---- -
- {{ApiRef("Document")}}
-

Document.createTreeWalker() 方法,能建立一個 {{domxref("TreeWalker")}} 物件並傳回.

-

語法

-
treeWalker = document.createTreeWalker(root, whatToShow, filter, entityReferenceExpansion);
-
-

參數

-
-
- root
-
- 是這個 {{domxref("TreeWalker")}} 遍歷的根節點(root {{domxref("Node")}}). Typically this will be an element owned by the document.
-
- whatToShow {{optional_inline}}
-
- Is an optional unsigned long representing a bitmask created by combining the constant properties of NodeFilter. 它是一種方便的方法,用來過濾某些類型的節點。 It defaults to 0xFFFFFFFF representing the SHOW_ALL constant.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant數值說明
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)顯示所有節點.
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2Shows attribute {{ domxref("Attr") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Attr") }} node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree.
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8Shows {{ domxref("CDATASection") }} nodes.
NodeFilter.SHOW_COMMENT128Shows {{ domxref("Comment") }} nodes.
NodeFilter.SHOW_DOCUMENT256Shows {{ domxref("Document") }} nodes.
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024Shows {{ domxref("DocumentFragment") }} nodes.
NodeFilter.SHOW_DOCUMENT_TYPE512Shows {{ domxref("DocumentType") }} nodes.
NodeFilter.SHOW_ELEMENT1Shows {{ domxref("Element") }} nodes.
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32Shows {{ domxref("Entity") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Entity") }} node as its root; in this case, it means that the {{ domxref("Entity") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16Shows {{ domxref("EntityReference") }} nodes.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048Shows {{ domxref("Notation") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with a {{ domxref("Notation") }} node as its root; in this case, it means that the {{ domxref("Notation") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64Shows {{ domxref("ProcessingInstruction") }} nodes.
NodeFilter.SHOW_TEXT4顯示文字節點({{ domxref("Text") }} nodes).
-
-
- filter {{optional_inline}}
-
- 是一個可選的 {{domxref("NodeFilter")}}, 這是一個物件有著 acceptNode 方法, 這方法被 {{domxref("TreeWalker")}} 呼叫來決定是否接受通過 whatToShow 檢查的節點.
-
- entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
-
- Is a {{domxref("Boolean")}} flag indicating if when discarding an {{domxref("EntityReference")}} its whole sub-tree must be discarded at the same time.
-
-

Example

-

The following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptNode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.

-
var treeWalker = document.createTreeWalker(
-  document.body,
-  NodeFilter.SHOW_ELEMENT,
-  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
-  false
-);
-
-var nodeList = [];
-
-while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
-
-

Specifications

- - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-createtreewalker', 'Document.createTreeWalker')}}{{Spec2('DOM WHATWG')}}Removed the expandEntityReferences parameter.
- Made the whatToShow and filter parameters optionals.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#NodeIteratorFactory-createTreeWalker', 'Document.createTreeWalker')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
-

Browser compatibility

-

{{CompatibilityTable}}

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
whatToShow and filter optional1.0{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}1.0{{CompatGeckoDesktop("1.8.1")}}
- Removed in {{CompatGeckoDesktop("12")}}
9.09.03.0
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
whatToShow and filter optional{{CompatVersionUnknown}}{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}
- Removed in {{CompatGeckoDesktop("12")}}
{{CompatVersionUnknown}}9.03.0
-
-

See also

- diff --git a/files/zh-tw/web/api/document/createevent/index.html b/files/zh-tw/web/api/document/createevent/index.html new file mode 100644 index 0000000000..e3fd9dcd4f --- /dev/null +++ b/files/zh-tw/web/api/document/createevent/index.html @@ -0,0 +1,30 @@ +--- +title: Event.createEvent() +slug: Web/API/Event/createEvent +translation_of: Web/API/Document/createEvent +translation_of_original: Web/API/Event/createEvent +--- +

{{APIRef("DOM")}}

+ +

建立一個新的事件,該事件必須先以其 init() method 初始化才行。

+ +

語法

+ +
document.createEvent(type) 
+ +
+
type
+
一個 string 。表示所建立的事件名稱。
+
+ +

這個 method 會回傳一個新的 DOM {{ domxref("Event") }} object ,其事件類型為傳入的 type 。該事件必須先初始化才能使用。

+ +

範例

+ +
var newEvent = document.createEvent("UIEvents");
+ +

規格定義

+ + diff --git a/files/zh-tw/web/api/document/createtreewalker/index.html b/files/zh-tw/web/api/document/createtreewalker/index.html new file mode 100644 index 0000000000..9e74411a14 --- /dev/null +++ b/files/zh-tw/web/api/document/createtreewalker/index.html @@ -0,0 +1,224 @@ +--- +title: Document.createTreeWalker() +slug: Web/API/document.createTreeWalker +translation_of: Web/API/Document/createTreeWalker +--- +
+ {{ApiRef("Document")}}
+

Document.createTreeWalker() 方法,能建立一個 {{domxref("TreeWalker")}} 物件並傳回.

+

語法

+
treeWalker = document.createTreeWalker(root, whatToShow, filter, entityReferenceExpansion);
+
+

參數

+
+
+ root
+
+ 是這個 {{domxref("TreeWalker")}} 遍歷的根節點(root {{domxref("Node")}}). Typically this will be an element owned by the document.
+
+ whatToShow {{optional_inline}}
+
+ Is an optional unsigned long representing a bitmask created by combining the constant properties of NodeFilter. 它是一種方便的方法,用來過濾某些類型的節點。 It defaults to 0xFFFFFFFF representing the SHOW_ALL constant.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant數值說明
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)顯示所有節點.
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2Shows attribute {{ domxref("Attr") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Attr") }} node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree.
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8Shows {{ domxref("CDATASection") }} nodes.
NodeFilter.SHOW_COMMENT128Shows {{ domxref("Comment") }} nodes.
NodeFilter.SHOW_DOCUMENT256Shows {{ domxref("Document") }} nodes.
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024Shows {{ domxref("DocumentFragment") }} nodes.
NodeFilter.SHOW_DOCUMENT_TYPE512Shows {{ domxref("DocumentType") }} nodes.
NodeFilter.SHOW_ELEMENT1Shows {{ domxref("Element") }} nodes.
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32Shows {{ domxref("Entity") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Entity") }} node as its root; in this case, it means that the {{ domxref("Entity") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16Shows {{ domxref("EntityReference") }} nodes.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048Shows {{ domxref("Notation") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with a {{ domxref("Notation") }} node as its root; in this case, it means that the {{ domxref("Notation") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64Shows {{ domxref("ProcessingInstruction") }} nodes.
NodeFilter.SHOW_TEXT4顯示文字節點({{ domxref("Text") }} nodes).
+
+
+ filter {{optional_inline}}
+
+ 是一個可選的 {{domxref("NodeFilter")}}, 這是一個物件有著 acceptNode 方法, 這方法被 {{domxref("TreeWalker")}} 呼叫來決定是否接受通過 whatToShow 檢查的節點.
+
+ entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
+
+ Is a {{domxref("Boolean")}} flag indicating if when discarding an {{domxref("EntityReference")}} its whole sub-tree must be discarded at the same time.
+
+

Example

+

The following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptNode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.

+
var treeWalker = document.createTreeWalker(
+  document.body,
+  NodeFilter.SHOW_ELEMENT,
+  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+  false
+);
+
+var nodeList = [];
+
+while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
+
+

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-createtreewalker', 'Document.createTreeWalker')}}{{Spec2('DOM WHATWG')}}Removed the expandEntityReferences parameter.
+ Made the whatToShow and filter parameters optionals.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#NodeIteratorFactory-createTreeWalker', 'Document.createTreeWalker')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+

Browser compatibility

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
whatToShow and filter optional1.0{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}1.0{{CompatGeckoDesktop("1.8.1")}}
+ Removed in {{CompatGeckoDesktop("12")}}
9.09.03.0
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
whatToShow and filter optional{{CompatVersionUnknown}}{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}
+ Removed in {{CompatGeckoDesktop("12")}}
{{CompatVersionUnknown}}9.03.0
+
+

See also

+ 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 new file mode 100644 index 0000000000..ff4ecfe572 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/events/index.html @@ -0,0 +1,69 @@ +--- +title: 事件與DOM +slug: Web/API/Document_Object_Model/事件 +translation_of: 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/web/api/document_object_model/\344\272\213\344\273\266/index.html" "b/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" deleted file mode 100644 index ff4ecfe572..0000000000 --- "a/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: 事件與DOM -slug: Web/API/Document_Object_Model/事件 -translation_of: 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/web/api/elementcssinlinestyle/style/index.html b/files/zh-tw/web/api/elementcssinlinestyle/style/index.html new file mode 100644 index 0000000000..e9e6d1171a --- /dev/null +++ b/files/zh-tw/web/api/elementcssinlinestyle/style/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLElement.style +slug: Web/API/HTMLElement/style +translation_of: Web/API/ElementCSSInlineStyle/style +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.The style property has the same (and highest) priority in the CSS cascade as an inline style declaration set via the style attribute.

+ +

設定 styles

+ +

Styles can be set by assigning a string directly to the style property (as in elt.style = "color: blue;") or by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...' ) as using elt.style.cssText = '...' or elt.setAttribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e. elt.style.fontSize, not elt.style.font-size)

+ +

範例

+ +
// Set multiple styles in a single statement
+elt.style.cssText = "color: blue; border: 1px solid black";
+// OR
+elt.setAttribute("style", "color:red; border: 1px solid blue;");
+
+
+elt.style.color = "blue";  // Set specific style while leaving other inline style values untouched
+
+ +

取得樣式資訊

+ +

The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the {{HTMLElement("head")}} section, or external style sheets. To get the values of all CSS properties for an element you should use {{domxref("window.getComputedStyle()")}} instead.

+ +

The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the computedStyle() method:

+ +
<!DOCTYPE HTML>
+<html>
+ <body style="font-weight:bold;">
+
+    <div style="color:red" id="myElement">..</div>
+
+ </body>
+</html>
+
+ +
var element = document.getElementById("myElement");
+var out = "";
+var elementStyle = element.style;
+var computedStyle = window.getComputedStyle(element, null);
+
+for (prop in elementStyle) {
+  if (elementStyle.hasOwnProperty(prop)) {
+    out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
+  }
+}
+console.log(out)
+
+ +

The output would be something like:

+ +
...
+fontWeight = '' > 'bold'
+color = 'red' > 'rgb(255, 0, 0)'
+...
+ +

Note the presence of the value "bold" for font-weight in the computed style and the absence of it in the element's style property

+ +

規範

+ +

DOM Level 2 Style: ElementCSSInlineStyle.style

+ +

瀏覽器相容性

+ +
+

Note: Starting in {{Gecko("2.0")}}, you can set SVG properties' values using the same shorthand syntax. For example:

+ +
element.style.fill = 'lime';
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/createevent/index.html b/files/zh-tw/web/api/event/createevent/index.html deleted file mode 100644 index e3fd9dcd4f..0000000000 --- a/files/zh-tw/web/api/event/createevent/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Event.createEvent() -slug: Web/API/Event/createEvent -translation_of: Web/API/Document/createEvent -translation_of_original: Web/API/Event/createEvent ---- -

{{APIRef("DOM")}}

- -

建立一個新的事件,該事件必須先以其 init() method 初始化才行。

- -

語法

- -
document.createEvent(type) 
- -
-
type
-
一個 string 。表示所建立的事件名稱。
-
- -

這個 method 會回傳一個新的 DOM {{ domxref("Event") }} object ,其事件類型為傳入的 type 。該事件必須先初始化才能使用。

- -

範例

- -
var newEvent = document.createEvent("UIEvents");
- -

規格定義

- - diff --git a/files/zh-tw/web/api/geolocation/using_geolocation/index.html b/files/zh-tw/web/api/geolocation/using_geolocation/index.html deleted file mode 100644 index cdc56770c4..0000000000 --- a/files/zh-tw/web/api/geolocation/using_geolocation/index.html +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: 地理位置定位 (Geolocation) -slug: Web/API/Geolocation/Using_geolocation -translation_of: Web/API/Geolocation_API ---- -

Web Apps 若需要使用者的位置,可透過 Geolocation API 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。

- -

地理位置定位 (Geolocation) 物件

- -

Geolocation API,是透過 navigator.geolocation 物件所發佈。

- -

若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:

- -
if ("geolocation" in navigator) {
-  /* geolocation is available */
-} else {
-  /* geolocation IS NOT available */
-}
-
- -
注意:在 Firefox 24 之後的版本,即使停用此 API,navigator 中的「geolocation」也同樣回傳 true。此問題已根據規格而於 Firefox 25 中修正 (bug 884921)。
- -

取得目前位置

- -

若要取得使用者目前的位置,可呼叫 getCurrentPosition() 函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。
- 若不論定位精確度而想儘快固定單一位置,則可使用 getCurrentPosition()。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,getCurrentPosition() 可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。

- -
-

注意:依預設值,getCurrentPosition() 將儘快回傳較低精確度的結果。若不論精確度而只要儘快獲得答案,則可使用 getCurrentPosition()。舉例來說,搭載 GPS 的裝置可能需要一段時間才能取得 GPS 定位資訊,所以可能將低精確度的資料 (IP 位置或 Wifi) 回傳至 getCurrentPosition()

-
- -
navigator.geolocation.getCurrentPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-});
- -

一旦取得定位位置之後,上列範例隨即將執行 do_something() 函式。

- -

觀看目前位置

- -

如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 watchPosition() 函式完成。watchPosition() 所具備的輸入參數與 getCurrentPosition() 相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 getCurrentPosition(),因此為選填

- -
-

注意:不需啟動 getCurrentPosition() 呼叫,亦可使用 watchPosition()

-
- -
var watchID = navigator.geolocation.watchPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-}
-);
- -

watchPosition() 函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 clearWatch() 函式,即可停止觀看使用者的位置。

- -
navigator.geolocation.clearWatch(watchID);
-
- -

微調回應

- -

getCurrentPosition()watchPosition() 均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 PositionOptions 物件 (選填)。

- -

watchPosition 的呼叫應類似如下:

- -
function geo_success(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-}
-
-function geo_error() {
-  alert("Sorry, no position available.");
-}
-
-var geo_options = {
-  enableHighAccuracy: true,
-  maximumAge        : 30000,
-  timeout           : 27000
-};
-
-var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
- -

現成的 watchPosition Demo:http://www.thedotproduct.org/experiments/geo/
- 

- -

敘述位置

- -

Position 物件參照 Coordinates 物件,即可敘述使用者的位置。

- -

處理錯誤

- -

在呼叫 getCurrentPosition()watchPosition() 時,若獲得錯誤回呼函式,則錯誤回呼函式的第一組參數將為 PositionError 物件:

- -
function errorCallback(error) {  alert('ERROR(' + error.code + '): ' + error.message);};
-
- -

地理位置定位實際範例

- -

HTML 內容

- -
<p><button onclick="geoFindMe()">Show my location</button></p>
-<div id="out"></div>
- -

JavaScript 內容

- -
function geoFindMe() {
-  var output = document.getElementById("out");
-
-  if (!navigator.geolocation){
-    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
-    return;
-  }
-
-  function success(position) {
-    var latitude  = position.coords.latitude;
-    var longitude = position.coords.longitude;
-
-    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
-
-    var img = new Image();
-    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
-
-    output.appendChild(img);
-  };
-
-  function error() {
-    output.innerHTML = "Unable to retrieve your location";
-  };
-
-  output.innerHTML = "<p>Locating…</p>";
-
-  navigator.geolocation.getCurrentPosition(success, error);
-}
-
- -

現場測試結果

- -

若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

- - -

{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}

- - -

請求權限

- -

addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 pref 參數所指定的偏好中。於 callback 參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 true,則附加元件才會存取地理位置定位資料。

- -
function prompt(window, pref, message, callback) {
-    let branch = Components.classes["@mozilla.org/preferences-service;1"]
-                           .getService(Components.interfaces.nsIPrefBranch);
-
-    if (branch.getPrefType(pref) === branch.PREF_STRING) {
-        switch (branch.getCharPref(pref)) {
-        case "always":
-            return callback(true);
-        case "never":
-            return callback(false);
-        }
-    }
-
-    let done = false;
-
-    function remember(value, result) {
-        return function() {
-            done = true;
-            branch.setCharPref(pref, value);
-            callback(result);
-        }
-    }
-
-    let self = window.PopupNotifications.show(
-        window.gBrowser.selectedBrowser,
-        "geolocation",
-        message,
-        "geo-notification-icon",
-        {
-            label: "Share Location",
-            accessKey: "S",
-            callback: function(notification) {
-                done = true;
-                callback(true);
-            }
-        }, [
-            {
-                label: "Always Share",
-                accessKey: "A",
-                callback: remember("always", true)
-            },
-            {
-                label: "Never Share",
-                accessKey: "N",
-                callback: remember("never", false)
-            }
-        ], {
-            eventCallback: function(event) {
-                if (event === "dismissed") {
-                    if (!done) callback(false);
-                    done = true;
-                    window.PopupNotifications.remove(self);
-                }
-            },
-            persistWhileVisible: true
-        });
-}
-
-prompt(window,
-       "extensions.foo-addon.allowGeolocation",
-       "Foo Add-on wants to know your location.",
-       function callback(allowed) { alert(allowed); });
-
- -

瀏覽器相容性

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
瀏覽器基本支援Geolocation Level 2
Internet ExplorerIE9 RC---
Firefox (Gecko)3.5 (1.9.1)---
Opera10.60---
Safari | Chrome | WebKit5 | 5 | 533---
- -

Gecko 註記

- -

Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 Mozilla 的隱私權政策Google 的隱私權政策。其內將詳述資料的使用方式。

- -

Firefox 3.6 (Gecko 1.9.2) 新支援了 GPSD (GPS daemon) 服務,適合 Linux 的地理位置定位。

- -

另請參閱

- - diff --git a/files/zh-tw/web/api/geolocation_api/index.html b/files/zh-tw/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..cdc56770c4 --- /dev/null +++ b/files/zh-tw/web/api/geolocation_api/index.html @@ -0,0 +1,251 @@ +--- +title: 地理位置定位 (Geolocation) +slug: Web/API/Geolocation/Using_geolocation +translation_of: Web/API/Geolocation_API +--- +

Web Apps 若需要使用者的位置,可透過 Geolocation API 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。

+ +

地理位置定位 (Geolocation) 物件

+ +

Geolocation API,是透過 navigator.geolocation 物件所發佈。

+ +

若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:

+ +
if ("geolocation" in navigator) {
+  /* geolocation is available */
+} else {
+  /* geolocation IS NOT available */
+}
+
+ +
注意:在 Firefox 24 之後的版本,即使停用此 API,navigator 中的「geolocation」也同樣回傳 true。此問題已根據規格而於 Firefox 25 中修正 (bug 884921)。
+ +

取得目前位置

+ +

若要取得使用者目前的位置,可呼叫 getCurrentPosition() 函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。
+ 若不論定位精確度而想儘快固定單一位置,則可使用 getCurrentPosition()。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,getCurrentPosition() 可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。

+ +
+

注意:依預設值,getCurrentPosition() 將儘快回傳較低精確度的結果。若不論精確度而只要儘快獲得答案,則可使用 getCurrentPosition()。舉例來說,搭載 GPS 的裝置可能需要一段時間才能取得 GPS 定位資訊,所以可能將低精確度的資料 (IP 位置或 Wifi) 回傳至 getCurrentPosition()

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

一旦取得定位位置之後,上列範例隨即將執行 do_something() 函式。

+ +

觀看目前位置

+ +

如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 watchPosition() 函式完成。watchPosition() 所具備的輸入參數與 getCurrentPosition() 相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 getCurrentPosition(),因此為選填

+ +
+

注意:不需啟動 getCurrentPosition() 呼叫,亦可使用 watchPosition()

+
+ +
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+);
+ +

watchPosition() 函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 clearWatch() 函式,即可停止觀看使用者的位置。

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

微調回應

+ +

getCurrentPosition()watchPosition() 均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 PositionOptions 物件 (選填)。

+ +

watchPosition 的呼叫應類似如下:

+ +
function geo_success(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+
+function geo_error() {
+  alert("Sorry, no position available.");
+}
+
+var geo_options = {
+  enableHighAccuracy: true,
+  maximumAge        : 30000,
+  timeout           : 27000
+};
+
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+ +

現成的 watchPosition Demo:http://www.thedotproduct.org/experiments/geo/
+ 

+ +

敘述位置

+ +

Position 物件參照 Coordinates 物件,即可敘述使用者的位置。

+ +

處理錯誤

+ +

在呼叫 getCurrentPosition()watchPosition() 時,若獲得錯誤回呼函式,則錯誤回呼函式的第一組參數將為 PositionError 物件:

+ +
function errorCallback(error) {  alert('ERROR(' + error.code + '): ' + error.message);};
+
+ +

地理位置定位實際範例

+ +

HTML 內容

+ +
<p><button onclick="geoFindMe()">Show my location</button></p>
+<div id="out"></div>
+ +

JavaScript 內容

+ +
function geoFindMe() {
+  var output = document.getElementById("out");
+
+  if (!navigator.geolocation){
+    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
+    return;
+  }
+
+  function success(position) {
+    var latitude  = position.coords.latitude;
+    var longitude = position.coords.longitude;
+
+    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
+
+    var img = new Image();
+    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
+
+    output.appendChild(img);
+  };
+
+  function error() {
+    output.innerHTML = "Unable to retrieve your location";
+  };
+
+  output.innerHTML = "<p>Locating…</p>";
+
+  navigator.geolocation.getCurrentPosition(success, error);
+}
+
+ +

現場測試結果

+ +

若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

+ + +

{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}

+ + +

請求權限

+ +

addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 pref 參數所指定的偏好中。於 callback 參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 true,則附加元件才會存取地理位置定位資料。

+ +
function prompt(window, pref, message, callback) {
+    let branch = Components.classes["@mozilla.org/preferences-service;1"]
+                           .getService(Components.interfaces.nsIPrefBranch);
+
+    if (branch.getPrefType(pref) === branch.PREF_STRING) {
+        switch (branch.getCharPref(pref)) {
+        case "always":
+            return callback(true);
+        case "never":
+            return callback(false);
+        }
+    }
+
+    let done = false;
+
+    function remember(value, result) {
+        return function() {
+            done = true;
+            branch.setCharPref(pref, value);
+            callback(result);
+        }
+    }
+
+    let self = window.PopupNotifications.show(
+        window.gBrowser.selectedBrowser,
+        "geolocation",
+        message,
+        "geo-notification-icon",
+        {
+            label: "Share Location",
+            accessKey: "S",
+            callback: function(notification) {
+                done = true;
+                callback(true);
+            }
+        }, [
+            {
+                label: "Always Share",
+                accessKey: "A",
+                callback: remember("always", true)
+            },
+            {
+                label: "Never Share",
+                accessKey: "N",
+                callback: remember("never", false)
+            }
+        ], {
+            eventCallback: function(event) {
+                if (event === "dismissed") {
+                    if (!done) callback(false);
+                    done = true;
+                    window.PopupNotifications.remove(self);
+                }
+            },
+            persistWhileVisible: true
+        });
+}
+
+prompt(window,
+       "extensions.foo-addon.allowGeolocation",
+       "Foo Add-on wants to know your location.",
+       function callback(allowed) { alert(allowed); });
+
+ +

瀏覽器相容性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
瀏覽器基本支援Geolocation Level 2
Internet ExplorerIE9 RC---
Firefox (Gecko)3.5 (1.9.1)---
Opera10.60---
Safari | Chrome | WebKit5 | 5 | 533---
+ +

Gecko 註記

+ +

Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 Mozilla 的隱私權政策Google 的隱私權政策。其內將詳述資料的使用方式。

+ +

Firefox 3.6 (Gecko 1.9.2) 新支援了 GPSD (GPS daemon) 服務,適合 Linux 的地理位置定位。

+ +

另請參閱

+ + diff --git a/files/zh-tw/web/api/htmlelement/dataset/index.html b/files/zh-tw/web/api/htmlelement/dataset/index.html deleted file mode 100644 index 690f8e1189..0000000000 --- a/files/zh-tw/web/api/htmlelement/dataset/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: HTMLElement.dataset -slug: Web/API/HTMLElement/dataset -translation_of: Web/API/HTMLOrForeignElement/dataset ---- -

{{ APIRef("HTML DOM") }}

- -

HTMLElement.dataset 允許在讀取與寫入模式時使用HTML或DOM裡,所有設置在元件上的自定義資料屬性(data-*)。他是一個DOMStringMap,每個項目表示一個不同的資料屬性。須注意的是,資料集(dataset)可以被讀取,但不能直接被修改。所有修改必須經由其眾多"屬性"才行,也就是資料屬性。另外,雖然HTML data- 屬性與它相關的 DOM dataset. 名稱不同,但是他們總是有相似之處: 

- - - -

除了以下的資訊之外,你也可以在 Using data attributes.此篇文章找到使用HTML資料屬性的用法。

- -

名稱變換

- -

 

- -

dash-style 到 camelCase: 將自訂義的資料屬性名稱變換至{{ domxref("DOMStringMap") }}各項目的key值,需根據以下規則:

- - - -

camelCase 到 dash-style: 與上述相反,將key值轉為資料屬性名稱,需根據以下規則:

- - - -

上面所提的限制是為了確保兩個轉換方法互為相反。

- -

舉例來說,資料屬性名稱 data-abc-def 之對應key值為abcDef

- -

 

- -

存取數值

- - - -

語法

- - - -

範例

- -
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
-
-let el = document.querySelector('#user');
-
-// el.id == 'user'
-// el.dataset.id === '1234567890'
-// el.dataset.user === 'johndoe'
-// el.dataset.dateOfBirth === ''
-
-el.dataset.dateOfBirth = '1960-10-03'; // 設定 DOB.
-
-// 'someDataAttr' in el.dataset === false
-el.dataset.someDataAttr = 'mydata';
-// 'someDataAttr' in el.dataset === true
-
- -

規範

- - - - - - - - - - - - - - - - - - - - - - - - -
規範狀態備註
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
- -

瀏覽器相容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - -
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援8{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}1111.106
-
- -
- - - - - - - - - - - - - - - - - - - - - -
功能AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(6)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

參見

- - diff --git a/files/zh-tw/web/api/htmlelement/innertext/index.html b/files/zh-tw/web/api/htmlelement/innertext/index.html new file mode 100644 index 0000000000..4c8a4272fc --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/innertext/index.html @@ -0,0 +1,86 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

概述

+ +

Node.innerText 是一個代表節點及其後代之「已渲染」(rendered)文字內容的屬性。如同一個存取器,Node.innerText 近似於使用者利用游標選取成高亮後複製至剪貼簿之元素的內容。此功能最初由 Internet Explorer 提供,並在被所有主要瀏覽器採納之後,於 2016 年正式成為 HTML 標準。

+ +

{{domxref("Node.textContent")}} 屬性是一個相似的選擇,但兩者之間仍有非常不同的差異。

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{ CompatGeckoDesktop(45) }}69.6 (probably earlier)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.3 (probably earlier){{ CompatGeckoMobile(45) }}10 (probably earlier)124.1 (probably earlier)
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlelement/style/index.html b/files/zh-tw/web/api/htmlelement/style/index.html deleted file mode 100644 index e9e6d1171a..0000000000 --- a/files/zh-tw/web/api/htmlelement/style/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: HTMLElement.style -slug: Web/API/HTMLElement/style -translation_of: Web/API/ElementCSSInlineStyle/style ---- -
{{ APIRef("HTML DOM") }}
- -

The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.The style property has the same (and highest) priority in the CSS cascade as an inline style declaration set via the style attribute.

- -

設定 styles

- -

Styles can be set by assigning a string directly to the style property (as in elt.style = "color: blue;") or by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...' ) as using elt.style.cssText = '...' or elt.setAttribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e. elt.style.fontSize, not elt.style.font-size)

- -

範例

- -
// Set multiple styles in a single statement
-elt.style.cssText = "color: blue; border: 1px solid black";
-// OR
-elt.setAttribute("style", "color:red; border: 1px solid blue;");
-
-
-elt.style.color = "blue";  // Set specific style while leaving other inline style values untouched
-
- -

取得樣式資訊

- -

The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the {{HTMLElement("head")}} section, or external style sheets. To get the values of all CSS properties for an element you should use {{domxref("window.getComputedStyle()")}} instead.

- -

The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the computedStyle() method:

- -
<!DOCTYPE HTML>
-<html>
- <body style="font-weight:bold;">
-
-    <div style="color:red" id="myElement">..</div>
-
- </body>
-</html>
-
- -
var element = document.getElementById("myElement");
-var out = "";
-var elementStyle = element.style;
-var computedStyle = window.getComputedStyle(element, null);
-
-for (prop in elementStyle) {
-  if (elementStyle.hasOwnProperty(prop)) {
-    out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
-  }
-}
-console.log(out)
-
- -

The output would be something like:

- -
...
-fontWeight = '' > 'bold'
-color = 'red' > 'rgb(255, 0, 0)'
-...
- -

Note the presence of the value "bold" for font-weight in the computed style and the absence of it in the element's style property

- -

規範

- -

DOM Level 2 Style: ElementCSSInlineStyle.style

- -

瀏覽器相容性

- -
-

Note: Starting in {{Gecko("2.0")}}, you can set SVG properties' values using the same shorthand syntax. For example:

- -
element.style.fill = 'lime';
-
- -

參見

- - diff --git a/files/zh-tw/web/api/htmlmediaelement/abort_event/index.html b/files/zh-tw/web/api/htmlmediaelement/abort_event/index.html new file mode 100644 index 0000000000..e0330135f4 --- /dev/null +++ b/files/zh-tw/web/api/htmlmediaelement/abort_event/index.html @@ -0,0 +1,68 @@ +--- +title: abort +slug: Web/Events/abort +translation_of: Web/API/HTMLMediaElement/abort_event +translation_of_original: Web/Events/abort +--- +

當資源載入被拒絕時將會觸發abort事件。

+ +

一般資訊

+ +
+
規範
+
DOM L3
+
介面
+
若由使用者介面產生,為UIEvent,否則為Event。
+
是否向上(冒泡)
+
+
是否為可取消
+
+
目標對象
+
Element
+
預設行為
+
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性型態描述
target {{readonlyInline}}EventTarget事件的目標對象 (DOM樹中最頂層的對象)。
type {{readonlyInline}}DOMString事件的型態。
bubbles {{readonlyInline}}Boolean事件是否向上冒泡。
cancelable {{readonlyInline}}Boolean事件是否能夠取消。
view {{readonlyInline}}WindowProxydocument.defaultView (該文檔(Document)的window)
detail {{readonlyInline}}long (float)0.
diff --git a/files/zh-tw/web/api/htmlorforeignelement/dataset/index.html b/files/zh-tw/web/api/htmlorforeignelement/dataset/index.html new file mode 100644 index 0000000000..690f8e1189 --- /dev/null +++ b/files/zh-tw/web/api/htmlorforeignelement/dataset/index.html @@ -0,0 +1,167 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLElement.dataset 允許在讀取與寫入模式時使用HTML或DOM裡,所有設置在元件上的自定義資料屬性(data-*)。他是一個DOMStringMap,每個項目表示一個不同的資料屬性。須注意的是,資料集(dataset)可以被讀取,但不能直接被修改。所有修改必須經由其眾多"屬性"才行,也就是資料屬性。另外,雖然HTML data- 屬性與它相關的 DOM dataset. 名稱不同,但是他們總是有相似之處: 

+ + + +

除了以下的資訊之外,你也可以在 Using data attributes.此篇文章找到使用HTML資料屬性的用法。

+ +

名稱變換

+ +

 

+ +

dash-style 到 camelCase: 將自訂義的資料屬性名稱變換至{{ domxref("DOMStringMap") }}各項目的key值,需根據以下規則:

+ + + +

camelCase 到 dash-style: 與上述相反,將key值轉為資料屬性名稱,需根據以下規則:

+ + + +

上面所提的限制是為了確保兩個轉換方法互為相反。

+ +

舉例來說,資料屬性名稱 data-abc-def 之對應key值為abcDef

+ +

 

+ +

存取數值

+ + + +

語法

+ + + +

範例

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
+
+let el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+el.dataset.dateOfBirth = '1960-10-03'; // 設定 DOB.
+
+// 'someDataAttr' in el.dataset === false
+el.dataset.someDataAttr = 'mydata';
+// 'someDataAttr' in el.dataset === true
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援8{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}1111.106
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(6)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/messageevent/index.html b/files/zh-tw/web/api/messageevent/index.html new file mode 100644 index 0000000000..f5c0212f78 --- /dev/null +++ b/files/zh-tw/web/api/messageevent/index.html @@ -0,0 +1,80 @@ +--- +title: MessageEvent +slug: WebSockets/WebSockets_reference/MessageEvent +tags: + - WebSockets +translation_of: Web/API/MessageEvent +--- +

{{ draft() }}

+

當伺服器傳來資料時,客戶端會收到一個 MessageEvent,由 WebSocket 物件 onmessage 表示的監聽器接收。

+

屬性

+ + + + + + + + + + + + + +
屬性形態描述
data{{ domxref("DOMString") }} | {{ domxref("Blob") }} | ArrayBuffer伺服器傳來的資料。
+

參見

+ +

瀏覽器兼容

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{ CompatUnknown() }}{{ CompatGeckoDesktop("2.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

Gecko 備註

+
+

{{ gecko_callout_heading("6.0") }}

+

此時此刻,Gecko 不支援 ArrayBuffer 或 {{ domxref("Blob") }} 作為 data

+
+

{{ languages ( {"en": "en/WebSockets/WebSockets_reference/MessageEvent"} ) }}

diff --git a/files/zh-tw/web/api/node/innertext/index.html b/files/zh-tw/web/api/node/innertext/index.html deleted file mode 100644 index 4c8a4272fc..0000000000 --- a/files/zh-tw/web/api/node/innertext/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Node.innerText -slug: Web/API/Node/innerText -translation_of: Web/API/HTMLElement/innerText ---- -
{{APIRef("DOM")}}
- -

概述

- -

Node.innerText 是一個代表節點及其後代之「已渲染」(rendered)文字內容的屬性。如同一個存取器,Node.innerText 近似於使用者利用游標選取成高亮後複製至剪貼簿之元素的內容。此功能最初由 Internet Explorer 提供,並在被所有主要瀏覽器採納之後,於 2016 年正式成為 HTML 標準。

- -

{{domxref("Node.textContent")}} 屬性是一個相似的選擇,但兩者之間仍有非常不同的差異。

- -

規範

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
- -

瀏覽器相容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{ CompatGeckoDesktop(45) }}69.6 (probably earlier)3
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.3 (probably earlier){{ CompatGeckoMobile(45) }}10 (probably earlier)124.1 (probably earlier)
-
- -

參見

- - diff --git a/files/zh-tw/web/api/performance.timing/index.html b/files/zh-tw/web/api/performance.timing/index.html deleted file mode 100644 index 33d0a54171..0000000000 --- a/files/zh-tw/web/api/performance.timing/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Performance.timing -slug: Web/API/Performance.timing -tags: - - API - - Navigation Timing - - Performance - - Property - - Read-only - - 唯讀 - - 屬性 - - 效能 -translation_of: Web/API/Performance/timing ---- -

{{APIRef("Performance")}}

- -

摘要

- -

Performance.timing 是唯讀的屬性,傳回的 {{domxref("PerformanceTiming")}} 物件當中包含了效能與時間延遲相關的資訊。

- -

語法

- -
timingInfo = performance.timing;
- -

規格

- - - - - - - - - - - - - - -
規格狀態備註
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.timing')}}{{Spec2('Navigation Timing')}}初步定義
- -

瀏覽器支援狀況

- -
-
- - -

{{Compat("api.Performance.timing")}}

-
-
- -

參照

- - diff --git a/files/zh-tw/web/api/performance/timing/index.html b/files/zh-tw/web/api/performance/timing/index.html new file mode 100644 index 0000000000..33d0a54171 --- /dev/null +++ b/files/zh-tw/web/api/performance/timing/index.html @@ -0,0 +1,56 @@ +--- +title: Performance.timing +slug: Web/API/Performance.timing +tags: + - API + - Navigation Timing + - Performance + - Property + - Read-only + - 唯讀 + - 屬性 + - 效能 +translation_of: Web/API/Performance/timing +--- +

{{APIRef("Performance")}}

+ +

摘要

+ +

Performance.timing 是唯讀的屬性,傳回的 {{domxref("PerformanceTiming")}} 物件當中包含了效能與時間延遲相關的資訊。

+ +

語法

+ +
timingInfo = performance.timing;
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.timing')}}{{Spec2('Navigation Timing')}}初步定義
+ +

瀏覽器支援狀況

+ +
+
+ + +

{{Compat("api.Performance.timing")}}

+
+
+ +

參照

+ + diff --git a/files/zh-tw/web/api/permissions_api/index.html b/files/zh-tw/web/api/permissions_api/index.html new file mode 100644 index 0000000000..d58d8466be --- /dev/null +++ b/files/zh-tw/web/api/permissions_api/index.html @@ -0,0 +1,85 @@ +--- +title: 權限 (Permissions) +slug: WebAPI/Permissions +translation_of: Web/API/Permissions_API +--- +

{{ draft() }}

+

{{ non-standard_header }}

+

{{ B2GOnlyHeader2('certified') }}

+

摘要

+

Permissions API 可顯示 Apps 所要求的所有權限,以利使用者管理。Apps 可透過此 API 而讀取其他 Apps 的權限並進一步變更。

+

透過 PermissionSettings 介面的 navigator.mozPermissionSettings 屬性,即可存取 Permission Manager。

+

已安裝 Apps 的權限

+

所有 Apps 均需透過自己的 manifest 檔案而要求權限。Apps 每次所使用的 API,均以「請求顯性權限 (Explicit Permission)」的 API 為主,並提示使用者是否通過權限。如果使用者選擇「不要再提示」,大概也就不太可能改變決定了。API 則能提供介面,以利使用者管理已發出的權限。

+

透過 PermissionSettings.get()set()isExplicit() 函式即可達到上述作業。

+

讀取權限

+

若要知道已發出權限的目前狀態,可使用 PermissionSettings.get() 函式。此函式可回傳字串,以顯示特定 Apps 權限的目前狀態。可能的數值有:

+
+
+ allow
+
+ 已通過該權限,且不需使用者的進一步互動。
+
+ denied
+
+ 已否決該權限;可能是系統或使用者所否決。
+
+ prompt
+
+ 代表該權限將以明顯的提示方法,詢問使用者是否給予權限。
+
+ unknown
+
+ 代表該 Apps 並未詢問此權限,也不會提示使用者是否給予權限。
+
+
// Let's check all installed apps
+var apps = navigator.mozApps.mgmt.getAll();
+
+apps.onsuccess = function () {
+  var permission = navigator.mozPermissionSettings;
+
+  // Let's check the permission of each app
+  apps.result.forEach(function (app) {
+    var request, appName = app.manifest.name;
+
+    for (request in app.manifest.permission) {
+      // Let's get the current permission for each permission request by the application
+      var p = permission.get(request, app.manifestUrl, app.origine, false);
+
+      console.log(appName + ' asked for "' + request + '" permission, which is "' + p + '"')
+    }
+  });
+}
+
+
+

設定權限

+

只要使用 PermissionSettings.set() 函式即可設定權限。可能的數值均與 get 函式所存取的相同。

+
+

注意:根據 Apps 權限的不同,某些可能為隱性 (Implicit) 權限。若因為某種理由,Apps 嘗試將權限變更為隱性權限,就會產生錯誤。為了避免這種錯誤,可透過 PermissionSettings.isExplicit() 函式而檢查是否為顯性權限。

+
+
// Let's check all installed apps
+var apps = navigator.mozApps.mgmt.getAll();
+
+apps.onsuccess = function () {
+  var permission = navigator.mozPermissionSettings;
+
+  // Let's grant the permission of each app
+  apps.result.forEach(function (app) {
+    var request, appName = app.manifest.name;
+
+    for (request in app.manifest.permission) {
+      // If the permission is not explicit
+      if (!permission.isExplicit(request, app.manifestUrl, app.origine, false) {
+        // Let's ask the user for all permissions requested by the application
+        permission.set(request, app.manifestUrl, app.origine, false);
+      }
+    }
+  });
+}
+

規格

+

不屬於任何規格。

+

另可參閱

+ diff --git a/files/zh-tw/web/api/web_video_text_tracks_format/index.html b/files/zh-tw/web/api/web_video_text_tracks_format/index.html deleted file mode 100644 index e565d2d129..0000000000 --- a/files/zh-tw/web/api/web_video_text_tracks_format/index.html +++ /dev/null @@ -1,691 +0,0 @@ ---- -title: WebVTT -slug: Web/API/Web_Video_Text_Tracks_Format -translation_of: Web/API/WebVTT_API ---- -

WebVTT 是一種 UTF-8 編碼的文字檔案格式,可藉由 {{ HTMLElement("track") }} 元素顯示加註時間資訊之文字軌,其主要設計目的是為 {{ HTMLElement("video") }} 顯示字幕。

- -

WebVTT 當中可以採用空白或分隔字元(tab)。

- -

WebVTT 的 MIME Type 為 text/vtt

- -

 

- -

WebVTT 文本

- -

WebVTT 檔的結構中,有兩項必備資訊、四項選用資訊。

- - - -
範例 1 - 最簡單的 WEBVTT 檔
- -
  WEBVTT
-
-
- -
範例 2 - 很簡單的 WebVTT 檔
- -
  WEBVTT - 這個檔案沒有時間節點
-
-
- -
範例 3 - 常見的 WebVTT 例子
- -
  WEBVTT - 這個檔案有時間節點
-
-  14
-  00:01:14.815 --> 00:01:18.114
-  - What?
-  - Where are we now?
-
-  15
-  00:01:18.171 --> 00:01:20.991
-  - This is big bat country.
-
-  16
-  00:01:21.058 --> 00:01:23.868
-  - [ Bats Screeching ]
-  - They won't get in your hair. They're after the bugs.
-
- -

 

- -

WebVTT 註解

- -

Comments are an optional component that can be used to add information to a WebVTT file. Comments are intended for those reading the file and are not seen by users. Comments may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

- -

註解中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。

- -

註解由三個部分組成:

- - - -
範例 4 - 常見 WebVTT 範例
- -
  NOTE 這行是註解
-
- -
範例 5 - 多行註解
- -
  NOTE
-  這也是註解,
-  只是拆成多行。
-
-  NOTE 當然也可以像這樣
-  來分行寫註解。
-
- -
範例 6 - 常見註解使用方式
- -
  WEBVTT - 翻譯我喜歡的影片字幕
-
-  NOTE
-  本字幕由 Kyle 翻譯,
-  希望可以讓我的朋友跟家人一同觀賞。
-
-  1
-  00:02:15.000 --> 00:02:20.000
-  - Ta en kopp varmt te.
-  - Det är inte varmt.
-
-  2
-  00:02:20.000 --> 00:02:25.000
-  - Har en kopp te.
-  - Det smakar som te.
-
-  NOTE This last line may not translate well.
-
-  3
-  00:02:25.000 --> 00:02:30.000
-  -Ta en kopp.
-
- -

 

- -

WebVTT 時間節點

- -

時間節點(cue)是具備單一開始時間、結束時間、文字內容的字幕區段。 Example 6 consists of the header, a blank line, and then five cues separated by blank lines. 時間節點由五個部分組成:

- - - -
範例7 - Example of a cue
- -
1 - Title Crawl
-00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-Some time ago in a place rather distant....
- -

 

- -

節點 ID

- -

此 ID 代表時間節點的名稱,可以用以在腳本語言中參照某段特定時間節點。ID 中禁用換行字元,也不可以包括「-->」字串。ID 最後必須以一個換行字元作為結束。

- -

雖然通常都用數字(1, 2, 3...)作為 ID,但規格上並不要求每個 ID 都是為一值。

- -
範例 8 - 範例 7 中的時間節點 ID
- -
1 - Title Crawl
- -
範例 9 - ID 常見用法
- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-3
-00:00:34.159 --> 00:00:35.743
-Third
-
- -

 

- -

時間資訊

- -

時間資訊標注了此段節點的出現時機,其中包括開始時間與結束時間。結束時間必須比開始時間晚,而開始時間必須比先前所有的開始時間晚,或至少是同一時間。

- -

不同時間節點可以設定為同時顯示,但若 WebVTT 檔案是用在 chapters({{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters),則不允許兩段節點同時出現。

- -

每項時間資訊都由五個部分組成:

- - - -

時間的表示方式,可以是以下兩種:

- - - -

其中的各元素說明如下:

- - - -
Example 10 - Basic cue timing examples
- -
00:22.230 --> 00:24.606
-00:30.739 --> 00:00:34.074
-00:00:34.159 --> 00:35.743
-00:00:35.827 --> 00:00:40.122
- -
Example 11 - Overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:05.000 --> 00:01:00.000
-00:00:30.000 --> 00:00:50.000
- -
Example 12 - Non-overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:10.000 --> 00:01:00.581
-00:01:00.581 --> 00:02:00.100
-00:02:01.000 --> 00:02:01.000
- -

 

- -

Cue Settings

- -

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

- -

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

- - - -
Example 13 - Cue setting examples
- -

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

- -
00:00:5.000 --> 00:00:10.000
-00:00:5.000 --> 00:00:10.000 line:63% position:72% align:start
-00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-00:00:5.000 --> 00:00:10.000 vertical:rt line:-1 align:end
-
- -

 

- -

文字內容

- -

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

- -

文字內容中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。若您使用 WebVTT 檔作為後設資料,則可不管這些限制。

- -

除了上述的三個跳脫字串外,還有其他四種跳脫字串,分列如下

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 6 - 跳脫字串
名稱字元跳脫字串
「與」&&amp;
小於<&lt;
大於>&gt;
左到右標記 &lrm;
右到左標記 &rlm;
不斷行空白 &nbsp;
- -

 

- -

文字內容中的標籤

- -

有很多標籤(例如 <bold>)可以用在文字內容中,但若 {{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters 時,其中所用的 WebVTT  檔案裡就不能使用標籤。

- - - -

 

- -

以下則需要開頭標籤與結束標籤(例如 <b>text</b>)。

- - - -

 

- -

瀏覽器支援

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援18 以上24 (預設為關閉)10 以上15.0 以上 7 以上
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IChrome for MobileOpera MobileSafari Mobile
基本支援4.4 以上       目前尚不支援         35.0 以上   21.0 以上7 以上
- -

 

- -

 

-
- -

規格

- - diff --git a/files/zh-tw/web/api/websocket/index.html b/files/zh-tw/web/api/websocket/index.html new file mode 100644 index 0000000000..8acd8d03d5 --- /dev/null +++ b/files/zh-tw/web/api/websocket/index.html @@ -0,0 +1,276 @@ +--- +title: WebSocket +slug: WebSockets/WebSockets_reference/WebSocket +tags: + - WebSockets +translation_of: Web/API/WebSocket +--- +

{{ SeeCompatTable() }}

+ +

{{ draft() }}

+ +

WebSocket 物件提供了建立、管理 WebSocket 伺服器連線的 API,它也有在連線中傳送、接收資料的能力。

+ +

方法一覽

+ + + + + + + + + + +
void close(in optional unsigned long code, in optional DOMString reason);
void send(in DOMString data);
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性形態描述
binaryType{{ DOMXref("DOMString") }}表示連線傳輸的二進制資料形態的字串,若使用 {{ domxref("Blob") }} 物件則為 "blob",使用 ArrayBuffer 物件則為 "arraybuffer"。
bufferedAmountunsigned long呼叫 {{ manch("send") }} 隊列但尚未傳輸至網路上資料的位元數。連線關閉時此值不會重設為零。連續呼叫 {{ manch("send") }} 會讓此值不斷上升。唯讀
extensions{{ DOMXref("DOMString") }}伺服器選擇的擴展。目前僅有空字串或表示資料經過壓縮的 "deflate-stream"。唯讀
onclose{{ domxref("EventListener") }}當 WebSocket 連線的 readyState 切換至 CLOSED 時呼叫的事件監聽器。監聽器接收命名為 "close" 的 CloseEvent
onerror{{ domxref("EventListener") }}當錯誤發生時呼叫的事件監聽器。事件為命名 "error" 的簡單事件。
onmessage{{ domxref("EventListener") }}當瀏覽器接收伺服器的訊息時呼叫的事件監聽器。監聽器接收命名為 "message" 的 MessageEvent
onopen{{ domxref("EventListener") }}當 WebSocket 連線的 readyState 切換至 OPEN 時呼叫的事件監聽器,表示連線已準備傳送、接收資料。事件為命名 "open" 的簡單事件。
protocol{{ DOMXref("DOMString") }}伺服器選擇的子協定,這是建立 WebSocket 物件時 protocols 參數裡的其中一個字串。
readyStateunsigned short連線的目前狀態,是就緒狀態常數的其中一個。唯讀
url{{ DOMXref("DOMString") }}建構方法解析出來的 URL,總是絕對 URL。唯讀
+ +

常數

+ +

就緒狀態常數

+ +

readyState 屬性使用以下常數描述 WebSocket 的連線狀態。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常數描述
CONNECTING0連線尚未打開。
OPEN1連線已打開,可以進行通訊。
CLOSING2連線正在進行關閉程序。
CLOSED3連線已關閉/連線不能打開。
+ +

方法

+ +

close()

+ +

關閉 WebSocket 連線/連線嘗試,若連線已為 CLOSED,此方法沒有作用。

+ +
void close(
+  in optional unsigned short code,
+  in optional DOMString reason
+);
+
+ +
參數
+ +
+
code {{ optional_inline() }}
+
表示狀態代碼,狀態代碼用以解釋連線關閉的原因。若未指定參數,預設值為 1000(表示正常的「事務完結(transaction complete)」關閉)。請參考 CloseEvent 頁面的狀態代碼列表,有所有的合法值。
+
reason {{ optional_inline() }}
+
解釋連線關閉原因的人類可讀字串,字串必不可大於 123 個 UTF-8 字符。
+
+ +
可丟例外
+ +
+
INVALID_ACCESS_ERR
+
指定不合法的 code
+
SYNTAX_ERR
+
reason 字串太長或是含有未配對的代理對。
+
+ +

send()

+ +

透過 WebSocket 連線傳輸資料至伺服器。

+ +
void send(
+  in DOMString data
+);
+
+void send(
+  in ArrayBuffer data
+);
+
+void send(
+  in Blob data
+);
+
+ +
參數
+ +
+
data
+
要傳送至伺服器的字串。
+
+ +
可丟例外
+ +
+
INVALID_STATE_ERR
+
目前連線不為 OPEN
+
SYNTAX_ERR
+
資料為帶有未配對代理對的字串。
+
+ +
註釋
+ +
+

{{ gecko_callout_heading("6.0") }}

+ +

Gecko send() 方法的實作與 Gecko 6.0 的規範有差別。Gecko 回傳一個 boolean 以表示連線是否仍處於開啟狀態(且資料成功隊列/傳輸)。另外,此時此刻,Gecko 不支援 ArrayBuffer 或 {{ domxref("Blob") }} 作為資料形態。

+
+ +

參見

+ + + +

瀏覽器兼容

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{ CompatUnknown() }}{{ CompatGeckoDesktop("2.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
子協定支援{{ CompatUnknown() }}{{ CompatGeckoDesktop("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{ CompatUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
子協定支援{{ CompatUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Gecko 備註

+ +

自從 Gecko 6.0,建構方法有前輟,須使用 MozWebSocket()

+ +
var mySocket = new MozWebSocket("http://www.example.com/socketserver");
+
+ +

{{ languages ( {"en": "en/WebSockets/WebSockets_reference/WebSocket"} ) }}

diff --git a/files/zh-tw/web/api/websockets_api/index.html b/files/zh-tw/web/api/websockets_api/index.html new file mode 100644 index 0000000000..3cbb630f41 --- /dev/null +++ b/files/zh-tw/web/api/websockets_api/index.html @@ -0,0 +1,155 @@ +--- +title: WebSockets +slug: WebSockets +tags: + - WebSockets +translation_of: Web/API/WebSockets_API +--- +

{{ SeeCompatTable() }}

+

WebSocket 是一種讓瀏覽器與伺服器進行一段互動通訊的技術。這個 API 在不必輪詢(poll)伺服器下,讓使用者傳送訊息至伺服器並接受事件驅動回應。

+ + + + + + + +
+

文件

+
+
+ 製作 WebSocket 客戶端應用程式
+
+ 指導如何製作在瀏覽器上跑 WebSocket 客戶端的教程。
+
+ WebSockets 參考手冊
+
+ 客戶端的 WebSocket API 參考手冊。
+
+ The WebSocket protocol
+
+ WebSocket 協定參考。
+
+ Writing WebSocket servers
+
+ 處理 WebSocket 協定的伺服器端代碼書寫指引。
+
+

所有文件...

+
+

工具

+ +

 

+ +
+
+ AJAXJavaScript
+
+
+

參見

+ +

瀏覽器兼容

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
版本 -76 {{ obsolete_inline() }}6{{ CompatGeckoDesktop("2.0") }}{{ CompatNo() }}11.00 (禁用)5.0.1
協定版本 7{{ CompatNo() }} +

{{ CompatGeckoDesktop("6.0") }}

+
+ 請用 MozWebSocket
+
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
協定版本 1014 +

{{ CompatGeckoDesktop("7.0") }}

+
+ 請用 MozWebSocket
+
HTML5 Labs{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
版本 -76 {{ obsolete_inline() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
協定版本 7{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
協定版本 8 (IETF 草案 10){{ CompatUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

Gecko 附註

+

Firefox 的 WebSockets 支援正在持續追蹤發展中的 WebSocket 規範。Firefox 6 實作底層協定版號 7,Firefox 7 實作協定版號 8(IETF 草案 10 的內容)。Firefox mobile 在 7.0 版支援 WebSocket。

+
+

{{ gecko_callout_heading("6.0") }}

+

Gecko 6.0 {{ geckoRelease("6.0") }} 之前,不該存在的 WebSocket 物件使得某些開發者認為 WebSocket 服務沒有前輟,此物件已被更名為 MozWebSocket

+
+
+

{{ gecko_callout_heading("7.0") }}

+

自從 Gecko 7.0 {{ geckoRelease("7.0") }},偏好設定 network.websocket.max-connections 可以用來設定 WebSocket 連線同時開啟的最大個數。預設值為 200。

+
+
+ 警告:雖然不是唯一的理由,但是目前 WebSockets 被 Firefox 4 與 5 禁用的關鍵原因是一個協定設計上的安全問題,因此不建議在生產環境下使用這些 Firefox 版本的 WebSockets。若仍想測試 WebSockets,你可以開啟 about:config 並設定 network.websocket.enabled 的取值至 true,並需要同時設定 network.websocket.override-security-block 的取值至 true 才能允許 WebSocket 連線的初始化。
+

{{ HTML5ArticleTOC() }}

+

{{ languages ( {"en": "en/WebSockets", "es": "es/WebSockets"} ) }}

diff --git a/files/zh-tw/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/zh-tw/web/api/websockets_api/writing_websocket_client_applications/index.html new file mode 100644 index 0000000000..8f1299379f --- /dev/null +++ b/files/zh-tw/web/api/websockets_api/writing_websocket_client_applications/index.html @@ -0,0 +1,179 @@ +--- +title: 製作 WebSocket 客戶端應用程式 +slug: WebSockets/Writing_WebSocket_client_applications +tags: + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +

{{ draft() }}

+ +

WebSocket 是一種讓瀏覽器與伺服器進行一段互動通訊的技術。使用這項技術的 Webapp 可以直接進行即時通訊而不需要不斷對資料更改進行輪詢(polling)。

+ +
注:當我們的系統架構可以寄存 WebSocket 範例之後,我們會提供聊天/伺服器系統實例的幾個範例。
+ +

哪裡有 WebSocket

+ +

若 JavaScript 代碼的範疇是 {{ domxref("Window") }} 物件或是實作 {{ domxref("WorkerUtils") }} 的物件,則可使用 WebSocket API。也就是可以從 Web Workers 使用 WebSocket。

+ +
注:WebSockets API(與底層協定)的開發還在進展中,且目前不同瀏覽器(甚至瀏覽器的不同版本)有很多兼容問題。
+ +

建立一個 WebSocket 物件

+ +

你必須建立一個 WebSocket 物件才能讓瀏覽器/伺服器得以以 WebSocket 協定進行通訊,此物件在被建立之後會自動與伺服器連線。

+ +
注:別忘記在 Firefox 6.0 中 WebSocket 物件仍有前輟,所以在這裡須改成 MozWebSocket
+ +

WebSocket 的建構方法有一個必要參數與一個選擇參數:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString[] protocols
+);
+
+ +
+
url
+
連線用的 URL,WebSocket 伺服器會回應這個 URL。
+
+ 根據網際網路工程任務小組(Internet Engineering Task Force,IETF)定義之規範, URL 的協議類型必須是 ws:// (非加密連線)或是 wss:// (加密連線)
+
protocols {{ optional_inline() }}
+
一個表示協定的字串或者是一個表示協定的字串構成的陣列。這些字串可以用來指定子協定,因此一個伺服器可以實作多個 WebSocket 子協定(舉例來說,你可以讓一個伺服器處理不同種類的互動情形,各情形以 protocol 分別)。若不指定協定字串則預設值為空字串。
+
+ +

此建構方法可能拋出以下例外:

+ +
+
SECURITY_ERR
+
連線使用的埠被阻擋。
+
+ +

範例

+ +

此簡單範例建立了一個新的 WebSocket,連到位於 http://www.example.com/socketserver 的伺服器。指定的子協定是 "my-custom-protocol"。

+ +
var mySocket = new WebSocket("ws://www.example.com/socketserver", "my-custom-protocol");
+
+ +

回傳之後,mySocketreadyState 會變成 CONNECTING。當連線已可以傳輸資料時 readyState 會變成 OPEN

+ +

要建立一個連線但不指定單一個特定協定,可以指定一個協定構成的陣列:

+ +
var mySocket = new WebSocket("ws://www.example.com/socketserver", ["protocol1", "protocol2"]);
+
+ +

當連線建立的時候(也就是 readyState 變成而 OPEN 的時候),protocol 屬性會回傳伺服器選擇的協定。

+ +

傳資料給伺服器

+ +

連線開啟之後即可開始傳資料給伺服器。呼叫 WebSocketsend() 來發送訊息:

+ +
mySocket.send("這是伺服器正迫切需要的文字!");
+
+ +

可以被傳送的內容包括字串、Blob 或是 ArrayBuffer

+ +
注:Firefox 目前只支援字串傳送。
+ +

用 JSON 傳輸物件

+ +

有一個很方便的方法是用 JSON 傳送複雜的資料給伺服器,舉例來說,聊天程式可以設計一種協定,這個協定傳送以 JSON 封裝的資料封包:

+ +
// 透過伺服器傳送文字給所有使用者
+
+function sendText() {
+  var msg = {
+    type: "message",
+    text: document.getElementById("text").value,
+    id: clientID,
+    date: Date.now()
+  };
+
+  mySocket.send(JSON.stringify(msg));
+  document.getElementById("text").value = "";
+}
+
+ +

這份代碼先建立一個物件:msg,它包含伺服器處理訊息所需的種種資訊,然後呼叫 JSON.stringify() 使該物件轉換成 JSON 格式並呼叫 WebSocket 的 send() 方法來傳輸資料至伺服器。

+ +

從伺服器接收訊息

+ +

WebSockets 是一個事件驅動 API,當瀏覽器收到訊息時,一個「message」事件被傳入 onmessage 函數。使用以下方法開始傾聽傳入資料:

+ +
mySocket.onmessage = function(e) {
+  console.log(e.data);
+}
+
+ +

接收並解讀 JSON 物件

+ +

考慮先前在「用 JSON 傳輸物件」談起的聊天應用程式。客戶端可能收到的資料封包有幾種:

+ + + +

用來解讀傳入訊息的代碼可能像是:

+ +
connection.onmessage = function(evt) {
+  var f = document.getElementById("chatbox").contentDocument;
+  var text = "";
+  var msg = JSON.parse(evt.data);
+  var time = new Date(msg.date);
+  var timeStr = time.toLocaleTimeString();
+
+  switch(msg.type) {
+    case "id":
+      clientID = msg.id;
+      setUsername();
+      break;
+    case "username":
+      text = "<b>使用者 <em>" + msg.name + "</em> 登入於 " + timeStr + "</b><br>";
+      break;
+    case "message":
+      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
+      break;
+    case "rejectusername":
+      text = "<b>由於你選取的名字已被人使用,你的使用者名稱已被設置為 <em>" + msg.name + "</em>。";
+      break;
+    case "userlist":
+      var ul = "";
+      for (i=0; i < msg.users.length; i++) {
+        ul += msg.users[i] + "<br>";
+      }
+      document.getElementById("userlistbox").innerHTML = ul;
+      break;
+  }
+
+  if (text.length) {
+    f.write(text);
+    document.getElementById("chatbox").contentWindow.scrollByPages(1);
+  }
+};
+
+ +

這裡我們使用 JSON.parse() 使 JSON 物件轉換成原來的物件,檢驗並根據內容採取行動。

+ +

關閉連線

+ +

當你想結束 WebSocket 連線的時候,呼叫 WebSocket 的 close() 方法:

+ +
mySocket.close();
+
+ +

參考資料

+ +

IETF: The WebSocket protocol draft-abarth-thewebsocketprotocol-01

+ +

 

+ +

{{ languages ( {"en": "en/WebSockets/Writing_WebSocket_client_applications"} ) }}

+ +
+
diff --git a/files/zh-tw/web/api/webvtt_api/index.html b/files/zh-tw/web/api/webvtt_api/index.html new file mode 100644 index 0000000000..e565d2d129 --- /dev/null +++ b/files/zh-tw/web/api/webvtt_api/index.html @@ -0,0 +1,691 @@ +--- +title: WebVTT +slug: Web/API/Web_Video_Text_Tracks_Format +translation_of: Web/API/WebVTT_API +--- +

WebVTT 是一種 UTF-8 編碼的文字檔案格式,可藉由 {{ HTMLElement("track") }} 元素顯示加註時間資訊之文字軌,其主要設計目的是為 {{ HTMLElement("video") }} 顯示字幕。

+ +

WebVTT 當中可以採用空白或分隔字元(tab)。

+ +

WebVTT 的 MIME Type 為 text/vtt

+ +

 

+ +

WebVTT 文本

+ +

WebVTT 檔的結構中,有兩項必備資訊、四項選用資訊。

+ + + +
範例 1 - 最簡單的 WEBVTT 檔
+ +
  WEBVTT
+
+
+ +
範例 2 - 很簡單的 WebVTT 檔
+ +
  WEBVTT - 這個檔案沒有時間節點
+
+
+ +
範例 3 - 常見的 WebVTT 例子
+ +
  WEBVTT - 這個檔案有時間節點
+
+  14
+  00:01:14.815 --> 00:01:18.114
+  - What?
+  - Where are we now?
+
+  15
+  00:01:18.171 --> 00:01:20.991
+  - This is big bat country.
+
+  16
+  00:01:21.058 --> 00:01:23.868
+  - [ Bats Screeching ]
+  - They won't get in your hair. They're after the bugs.
+
+ +

 

+ +

WebVTT 註解

+ +

Comments are an optional component that can be used to add information to a WebVTT file. Comments are intended for those reading the file and are not seen by users. Comments may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

+ +

註解中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。

+ +

註解由三個部分組成:

+ + + +
範例 4 - 常見 WebVTT 範例
+ +
  NOTE 這行是註解
+
+ +
範例 5 - 多行註解
+ +
  NOTE
+  這也是註解,
+  只是拆成多行。
+
+  NOTE 當然也可以像這樣
+  來分行寫註解。
+
+ +
範例 6 - 常見註解使用方式
+ +
  WEBVTT - 翻譯我喜歡的影片字幕
+
+  NOTE
+  本字幕由 Kyle 翻譯,
+  希望可以讓我的朋友跟家人一同觀賞。
+
+  1
+  00:02:15.000 --> 00:02:20.000
+  - Ta en kopp varmt te.
+  - Det är inte varmt.
+
+  2
+  00:02:20.000 --> 00:02:25.000
+  - Har en kopp te.
+  - Det smakar som te.
+
+  NOTE This last line may not translate well.
+
+  3
+  00:02:25.000 --> 00:02:30.000
+  -Ta en kopp.
+
+ +

 

+ +

WebVTT 時間節點

+ +

時間節點(cue)是具備單一開始時間、結束時間、文字內容的字幕區段。 Example 6 consists of the header, a blank line, and then five cues separated by blank lines. 時間節點由五個部分組成:

+ + + +
範例7 - Example of a cue
+ +
1 - Title Crawl
+00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+Some time ago in a place rather distant....
+ +

 

+ +

節點 ID

+ +

此 ID 代表時間節點的名稱,可以用以在腳本語言中參照某段特定時間節點。ID 中禁用換行字元,也不可以包括「-->」字串。ID 最後必須以一個換行字元作為結束。

+ +

雖然通常都用數字(1, 2, 3...)作為 ID,但規格上並不要求每個 ID 都是為一值。

+ +
範例 8 - 範例 7 中的時間節點 ID
+ +
1 - Title Crawl
+ +
範例 9 - ID 常見用法
+ +
WEBVTT
+
+1
+00:00:22.230 --> 00:00:24.606
+This is the first subtitle.
+
+2
+00:00:30.739 --> 00:00:34.074
+This is the second.
+
+3
+00:00:34.159 --> 00:00:35.743
+Third
+
+ +

 

+ +

時間資訊

+ +

時間資訊標注了此段節點的出現時機,其中包括開始時間與結束時間。結束時間必須比開始時間晚,而開始時間必須比先前所有的開始時間晚,或至少是同一時間。

+ +

不同時間節點可以設定為同時顯示,但若 WebVTT 檔案是用在 chapters({{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters),則不允許兩段節點同時出現。

+ +

每項時間資訊都由五個部分組成:

+ + + +

時間的表示方式,可以是以下兩種:

+ + + +

其中的各元素說明如下:

+ + + +
Example 10 - Basic cue timing examples
+ +
00:22.230 --> 00:24.606
+00:30.739 --> 00:00:34.074
+00:00:34.159 --> 00:35.743
+00:00:35.827 --> 00:00:40.122
+ +
Example 11 - Overlapping cue timing examples
+ +
00:00:00.000 --> 00:00:10.000
+00:00:05.000 --> 00:01:00.000
+00:00:30.000 --> 00:00:50.000
+ +
Example 12 - Non-overlapping cue timing examples
+ +
00:00:00.000 --> 00:00:10.000
+00:00:10.000 --> 00:01:00.581
+00:01:00.581 --> 00:02:00.100
+00:02:01.000 --> 00:02:01.000
+ +

 

+ +

Cue Settings

+ +

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

+ +

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

+ + + +
Example 13 - Cue setting examples
+ +

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

+ +
00:00:5.000 --> 00:00:10.000
+00:00:5.000 --> 00:00:10.000 line:63% position:72% align:start
+00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+00:00:5.000 --> 00:00:10.000 vertical:rt line:-1 align:end
+
+ +

 

+ +

文字內容

+ +

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

+ +

文字內容中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。若您使用 WebVTT 檔作為後設資料,則可不管這些限制。

+ +

除了上述的三個跳脫字串外,還有其他四種跳脫字串,分列如下

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 6 - 跳脫字串
名稱字元跳脫字串
「與」&&amp;
小於<&lt;
大於>&gt;
左到右標記 &lrm;
右到左標記 &rlm;
不斷行空白 &nbsp;
+ +

 

+ +

文字內容中的標籤

+ +

有很多標籤(例如 <bold>)可以用在文字內容中,但若 {{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters 時,其中所用的 WebVTT  檔案裡就不能使用標籤。

+ + + +

 

+ +

以下則需要開頭標籤與結束標籤(例如 <b>text</b>)。

+ + + +

 

+ +

瀏覽器支援

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援18 以上24 (預設為關閉)10 以上15.0 以上 7 以上
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IChrome for MobileOpera MobileSafari Mobile
基本支援4.4 以上       目前尚不支援         35.0 以上   21.0 以上7 以上
+ +

 

+ +

 

+
+ +

規格

+ + diff --git a/files/zh-tw/web/api/window.history/index.html b/files/zh-tw/web/api/window.history/index.html deleted file mode 100644 index 67b79c5f82..0000000000 --- a/files/zh-tw/web/api/window.history/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Window.history -slug: Web/API/Window.history -translation_of: Web/API/Window/history ---- -

{{ APIRef }}

- -

Window.history 唯讀屬性會回傳一個 {{domxref("History")}} 物件,其提供了一個介面來操控瀏覽器的 session history 紀錄(為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面)。

- -

相關範例及細節請參考操控瀏覽器歷史紀錄一文。文章中解釋了在使用 pushState()replaceState() 方法前應該要知道的安全性功能。

- -

語法

- -
var historyObj = window.history;
-
- -

範例

- -
history.back();     // 相當於按下上一頁按鈕
-history.go(-1);     // 相當於 history.back();
-
- -

備註

- -

For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.

- -

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

- -

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

- -

規範

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/zh-tw/web/api/window.onpopstate/index.html b/files/zh-tw/web/api/window.onpopstate/index.html deleted file mode 100644 index d98464d356..0000000000 --- a/files/zh-tw/web/api/window.onpopstate/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: window.onpopstate -slug: Web/API/Window.onpopstate -translation_of: Web/API/WindowEventHandlers/onpopstate ---- -
{{ApiRef}} {{gecko_minversion_header("2")}}
- -

摘要

- -

視窗上 popstate 事件的事件處理器。

- -

在同一文件的當前歷史紀錄變動時,如果其變動介於兩個歷史紀錄間,popstate 就會被呼叫。如果當前的歷史紀錄是藉由呼叫 history.pushState() 建立,或曾被 history.replaceState() 修改過,popstate 事件的 state 屬性,將包含一份歷史紀錄的 state 物件。

- -

請注意:直接呼叫 history.pushState()history.replaceState() 不會驅動 popstate 事件。popstate 事件只會被瀏覽器的行為驅動,例如點擊上一頁按鈕(或透過 JavaScript 呼叫 history.back())。且此事件只會在用戶於同文件的兩個歷史紀錄間瀏覽時作動。

- -

在頁面載入時,不同瀏覽器具有不同的 popstate 行為。Chrome 與 Safari 會在頁面載入時觸發 popstate 事件,但 Firefox 則不會。

- -

語法

- -
window.onpopstate = funcRef;
-
- - - -

popstate 事件

- -

以下範例,位於 http://example.com/example.html 並執行下列程式的頁面,將會產生如標示的對話框:

- -
window.onpopstate = function(event) {
-  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
-};
-
-history.pushState({page: 1}, "title 1", "?page=1");
-history.pushState({page: 2}, "title 2", "?page=2");
-history.replaceState({page: 3}, "title 3", "?page=3");
-history.back(); // 跳出 "location: http://example.com/example.html?page=1, state: {"page":1}"
-history.back(); // 跳出 "location: http://example.com/example.html, state: null
-history.go(2);  // 跳出 "location: http://example.com/example.html?page=3, state: {"page":3}
-
- -

請注意,雖然原始的歷史紀錄(http://example.com/example.html)沒有關聯的 state 物件,在我們第二次呼叫 hitsory.back() 時仍然會觸發 popstate 事件

- -

標準

- - - -

請參照

- - diff --git a/files/zh-tw/web/api/window.requestanimationframe/index.html b/files/zh-tw/web/api/window.requestanimationframe/index.html deleted file mode 100644 index 55aa85d292..0000000000 --- a/files/zh-tw/web/api/window.requestanimationframe/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Window.requestAnimationFrame() -slug: Web/API/Window.requestAnimationFrame -translation_of: Web/API/window/requestAnimationFrame ---- -
{{APIRef}}
- -

window.requestAnimationFrame()方法通知瀏覽器我們想要產生動畫,並且要求瀏覽器在下次重繪畫面前呼叫特定函數更新動畫。這個方法接受一個引數作為下次重繪前調用的回呼函數。

- -
Note: 若是想要在下次重繪時產生另一個動畫,這個回呼函數內必須自行呼叫 requestAnimationFrame()。
- -

當準備好更新頁面上的動畫時應當呼叫這個方法。這表示向瀏覽器請求在下次重繪前呼叫這個動畫函數。回呼的次數通常落在每秒 60 次,但通常會根據 W3C 的建議符合多數瀏覽器重新整理的頻率。當頁面處於背景或隱藏狀態時 {{ HTMLElement("iframe") }} ,多數的瀏覽器會暫停 requestAnimationFrame() 的呼叫,從而改善效能表現及電池壽命。

- -

回呼方法會得到一個 {{domxref("DOMHighResTimeStamp")}} 的引數,作為指示目前的時間(基於 time origin 之後經過的毫秒數)。當 requestAnimationFrame() 佇列了數個回呼並且在同一幀開始觸發多個回呼時,儘管每一個之前的回呼在運作時會消耗一定的時間,但它們都會取得同樣的時間戳記。時間戳記是由十進位數字表示的毫秒且最小的精準度為 1 毫秒(1000 µs)。

- -

語法

- -
window.requestAnimationFrame(callback);
-
- -

參數

- -
-
回呼
-
當下次重新繪製時用於呼叫並更新動畫。回呼函數會得到一個引數—— {{domxref("DOMHighResTimeStamp")}} ——類似於由 {{domxref('performance.now()')}} 回傳的結果,其用於指示當 requestAnimationFrame() 開始執行回呼函數的時間。
-
- -

回傳值

- -

long 型別的整數值表示請求的 id,作為其進入回呼清單中的唯一識別。雖然回傳值是一個非零值,但不應該對其有其他任何的假設。將這個值傳遞給 {{domxref("window.cancelAnimationFrame()")}} 可以取消重新整理頁面回呼的請求

- -

範例

- -
var start = null;
-var element = document.getElementById('SomeElementYouWantToAnimate');
-
-function step(timestamp) {
-  if (!start) start = timestamp;
-  var progress = timestamp - start;
-  element.style.transform = 'translateX(' + Math.min(progress / 10, 200) + 'px)';
-  if (progress < 2000) {
-    window.requestAnimationFrame(step);
-  }
-}
-
-window.requestAnimationFrame(step);
-
- -

備註

- -

Edge 低於 17 的版本和 Internet Explorer 無法保證在繪製循環前觸發 requestAnimationFrame

- -

規格

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}No change, supersedes the previous one.
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}Initial definition
- -

瀏覽器相容性

- -
-

{{Compat("api.Window.requestAnimationFrame")}}

-
- -

其他參考

- - diff --git a/files/zh-tw/web/api/window/domcontentloaded_event/index.html b/files/zh-tw/web/api/window/domcontentloaded_event/index.html new file mode 100644 index 0000000000..0ec78423ec --- /dev/null +++ b/files/zh-tw/web/api/window/domcontentloaded_event/index.html @@ -0,0 +1,133 @@ +--- +title: DOMContentLoaded +slug: Web/Events/DOMContentLoaded +translation_of: Web/API/Window/DOMContentLoaded_event +--- +

DOMContentLoaded事件是當document被完整的讀取跟解析後就會被觸發,不會等待 stylesheets, 圖片和subframes完成讀取  (load事件可以用來作為判斷頁面已經完整讀取的方法).

+ +
+

Note: Stylesheet loads block script execution, 如果 <script> 被放在 <link rel="stylesheet" ...>後面的話, 須等到前面的stylesheet載入並完成解析,此時 DOMContentLoaded才會被觸發。

+
+ +

Speeding up

+ +

If you want DOM to get parsed as fast as possible after the user had requested the page, some things you could do is turn your JavaScript asynchronous and to optimize loading of stylesheets which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.

+ +

General info

+ +
+
Specification
+
HTML5
+
Interface
+
Event
+
Bubbles
+
Yes
+
Cancelable
+
Yes (although specified as a simple event that isn't cancelable)
+
Target
+
Document
+
Default Action
+
None.
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support0.2{{ CompatGeckoDesktop("1") }}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.

+ +

Cross-browser fallback

+ +

Internet Explorer 8 supports the <code>readystatechange</code> event, which can be used to detect that the DOM is ready. In earlier version of Internet Explorer, this state can be detected by regularily trying to execute <code>document.documentElement.doScroll("left");</code>, as this snippet will throw an error until the DOM is ready.

+ +

General-purpose JS libraries such as jQuery offer cross-browser methods to detect that the DOM is ready. There are also standalone scripts that offer this feature : contentloaded.js (supports only one listener) and jquery.documentReady.js (doesn't depend on jQuery, despite its name).

+ + + + diff --git a/files/zh-tw/web/api/window/history/index.html b/files/zh-tw/web/api/window/history/index.html new file mode 100644 index 0000000000..67b79c5f82 --- /dev/null +++ b/files/zh-tw/web/api/window/history/index.html @@ -0,0 +1,51 @@ +--- +title: Window.history +slug: Web/API/Window.history +translation_of: Web/API/Window/history +--- +

{{ APIRef }}

+ +

Window.history 唯讀屬性會回傳一個 {{domxref("History")}} 物件,其提供了一個介面來操控瀏覽器的 session history 紀錄(為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面)。

+ +

相關範例及細節請參考操控瀏覽器歷史紀錄一文。文章中解釋了在使用 pushState()replaceState() 方法前應該要知道的安全性功能。

+ +

語法

+ +
var historyObj = window.history;
+
+ +

範例

+ +
history.back();     // 相當於按下上一頁按鈕
+history.go(-1);     // 相當於 history.back();
+
+ +

備註

+ +

For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.

+ +

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

+ +

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/zh-tw/web/api/window/load_event/index.html b/files/zh-tw/web/api/window/load_event/index.html new file mode 100644 index 0000000000..7c6d314925 --- /dev/null +++ b/files/zh-tw/web/api/window/load_event/index.html @@ -0,0 +1,88 @@ +--- +title: load +slug: Web/Events/load +translation_of: Web/API/Window/load_event +--- +

load 事件發生在加載完目標資源、該資源依賴的其他資源時。

+ +

一般資訊

+ +
+
規範
+
DOM L3
+
介面
+
UIEvent
+
起泡事件
+
No
+
可取消
+
No
+
對象
+
Window
+
預設行為
+
None.
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
+ +

範例

+ +
<script>
+  window.addEventListener("load", function(event) {
+    console.log("All resources finished loading!");
+  });
+</script>
+
+ +

 

+ +

相關事件

+ + diff --git a/files/zh-tw/web/api/window/requestanimationframe/index.html b/files/zh-tw/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..55aa85d292 --- /dev/null +++ b/files/zh-tw/web/api/window/requestanimationframe/index.html @@ -0,0 +1,94 @@ +--- +title: Window.requestAnimationFrame() +slug: Web/API/Window.requestAnimationFrame +translation_of: Web/API/window/requestAnimationFrame +--- +
{{APIRef}}
+ +

window.requestAnimationFrame()方法通知瀏覽器我們想要產生動畫,並且要求瀏覽器在下次重繪畫面前呼叫特定函數更新動畫。這個方法接受一個引數作為下次重繪前調用的回呼函數。

+ +
Note: 若是想要在下次重繪時產生另一個動畫,這個回呼函數內必須自行呼叫 requestAnimationFrame()。
+ +

當準備好更新頁面上的動畫時應當呼叫這個方法。這表示向瀏覽器請求在下次重繪前呼叫這個動畫函數。回呼的次數通常落在每秒 60 次,但通常會根據 W3C 的建議符合多數瀏覽器重新整理的頻率。當頁面處於背景或隱藏狀態時 {{ HTMLElement("iframe") }} ,多數的瀏覽器會暫停 requestAnimationFrame() 的呼叫,從而改善效能表現及電池壽命。

+ +

回呼方法會得到一個 {{domxref("DOMHighResTimeStamp")}} 的引數,作為指示目前的時間(基於 time origin 之後經過的毫秒數)。當 requestAnimationFrame() 佇列了數個回呼並且在同一幀開始觸發多個回呼時,儘管每一個之前的回呼在運作時會消耗一定的時間,但它們都會取得同樣的時間戳記。時間戳記是由十進位數字表示的毫秒且最小的精準度為 1 毫秒(1000 µs)。

+ +

語法

+ +
window.requestAnimationFrame(callback);
+
+ +

參數

+ +
+
回呼
+
當下次重新繪製時用於呼叫並更新動畫。回呼函數會得到一個引數—— {{domxref("DOMHighResTimeStamp")}} ——類似於由 {{domxref('performance.now()')}} 回傳的結果,其用於指示當 requestAnimationFrame() 開始執行回呼函數的時間。
+
+ +

回傳值

+ +

long 型別的整數值表示請求的 id,作為其進入回呼清單中的唯一識別。雖然回傳值是一個非零值,但不應該對其有其他任何的假設。將這個值傳遞給 {{domxref("window.cancelAnimationFrame()")}} 可以取消重新整理頁面回呼的請求

+ +

範例

+ +
var start = null;
+var element = document.getElementById('SomeElementYouWantToAnimate');
+
+function step(timestamp) {
+  if (!start) start = timestamp;
+  var progress = timestamp - start;
+  element.style.transform = 'translateX(' + Math.min(progress / 10, 200) + 'px)';
+  if (progress < 2000) {
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+
+ +

備註

+ +

Edge 低於 17 的版本和 Internet Explorer 無法保證在繪製循環前觸發 requestAnimationFrame

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}No change, supersedes the previous one.
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}Initial definition
+ +

瀏覽器相容性

+ +
+

{{Compat("api.Window.requestAnimationFrame")}}

+
+ +

其他參考

+ + diff --git a/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html b/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html deleted file mode 100644 index 780e92fb84..0000000000 --- a/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: 自網頁添加搜尋引擎 -slug: Web/API/Window/sidebar/Adding_search_engines_from_Web_pages -tags: - - 搜尋模組 -translation_of: Web/OpenSearch -translation_of_original: Web/API/Window/sidebar/Adding_search_engines_from_Web_pages ---- -

Firefox 可以用 JavaScript 安裝搜尋引擎模組,且支援 OpenSearch 及 Sherlock 兩種模組格式。 -

-
註: 自 Firefox 2 起,偏好的模組格式為 OpenSearch。
-

當 JavaScript 程式碼要安裝新的搜尋模組時,Firefox 會詢問使用者是否允許安裝。 -

-

安裝 OpenSearch 模組

-

要安裝 OpenSearch 模組,必須使用 window.external.AddSearchProvider() DOM 方法。此方法的語法為: -

-
window.external.AddSearchProvider(搜尋模組 URL);
-
-

其中 搜尋模組 URL 為搜尋引擎模組之 XML 檔的絕對連結 URL。 -

-
注意: OpenSearch 自 Firefox 2 起的版本才支援。
-

安裝 Sherlock 模組

-

要安裝 Sherlock 模組,必須叫用 window.sidebar.addSearchEngine() 方法,語法為: -

-
window.sidebar.addSearchEngine(搜尋模組 URL, 圖示 URL, 建議名稱, 建議分類);
-
- -

Sherlock 的相關資訊可參考 http://developer.apple.com/macosx/sherlock/ -

-
-
-{{ languages( { "ca": "ca/Addici\u00f3_de_motors_de_cerca_a_les_p\u00e0gines_web", "en": "en/Adding_search_engines_from_web_pages", "es": "es/A\u00f1adir_motores_de_b\u00fasqueda_desde_p\u00e1ginas_web", "fr": "fr/Ajout_de_moteurs_de_recherche_depuis_des_pages_Web", "it": "it/Installare_plugin_di_ricerca_dalle_pagine_web", "ja": "ja/Adding_search_engines_from_web_pages", "pl": "pl/Dodawanie_wyszukiwarek_z_poziomu_stron_WWW" } ) }} diff --git a/files/zh-tw/web/api/windowbase64/index.html b/files/zh-tw/web/api/windowbase64/index.html deleted file mode 100644 index 6cf618070e..0000000000 --- a/files/zh-tw/web/api/windowbase64/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: WindowBase64 -slug: Web/API/WindowBase64 -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowBase64 ---- -

{{APIRef("HTML DOM")}}

- -

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

- -

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

- -

屬性

- -

This helper neither defines nor inherits any properties.

- -

方法

- -

This helper does not inherit any methods.

- -
-
{{domxref("WindowBase64.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowBase64.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
- -

規範

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

瀏覽器相容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

- -

參見

- - diff --git a/files/zh-tw/web/api/windoweventhandlers/onpopstate/index.html b/files/zh-tw/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..d98464d356 --- /dev/null +++ b/files/zh-tw/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,57 @@ +--- +title: window.onpopstate +slug: Web/API/Window.onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{ApiRef}} {{gecko_minversion_header("2")}}
+ +

摘要

+ +

視窗上 popstate 事件的事件處理器。

+ +

在同一文件的當前歷史紀錄變動時,如果其變動介於兩個歷史紀錄間,popstate 就會被呼叫。如果當前的歷史紀錄是藉由呼叫 history.pushState() 建立,或曾被 history.replaceState() 修改過,popstate 事件的 state 屬性,將包含一份歷史紀錄的 state 物件。

+ +

請注意:直接呼叫 history.pushState()history.replaceState() 不會驅動 popstate 事件。popstate 事件只會被瀏覽器的行為驅動,例如點擊上一頁按鈕(或透過 JavaScript 呼叫 history.back())。且此事件只會在用戶於同文件的兩個歷史紀錄間瀏覽時作動。

+ +

在頁面載入時,不同瀏覽器具有不同的 popstate 行為。Chrome 與 Safari 會在頁面載入時觸發 popstate 事件,但 Firefox 則不會。

+ +

語法

+ +
window.onpopstate = funcRef;
+
+ + + +

popstate 事件

+ +

以下範例,位於 http://example.com/example.html 並執行下列程式的頁面,將會產生如標示的對話框:

+ +
window.onpopstate = function(event) {
+  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // 跳出 "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // 跳出 "location: http://example.com/example.html, state: null
+history.go(2);  // 跳出 "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

請注意,雖然原始的歷史紀錄(http://example.com/example.html)沒有關聯的 state 物件,在我們第二次呼叫 hitsory.back() 時仍然會觸發 popstate 事件

+ +

標準

+ + + +

請參照

+ + diff --git a/files/zh-tw/web/api/windowtimers/index.html b/files/zh-tw/web/api/windowtimers/index.html deleted file mode 100644 index c38c15b821..0000000000 --- a/files/zh-tw/web/api/windowtimers/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: WindowTimers -slug: Web/API/WindowTimers -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowTimers ---- -
{{APIRef("HTML DOM")}}
- -

WindowTimers is a mixin used to provide utility methods which set and clear timers. No objects of this type exist; instead, its methods are available on {{domxref("Window")}} for the standard browsing scope, or on {{domxref("WorkerGlobalScope")}} for workers.

- -

屬性

- -

WindowTimers 介面沒有繼承也沒有定義任何屬性。

- -

方法

- -

除以下自身方法外,WindowTimers 介面提沒有任何繼承方法。

- -
-
{{domxref("WindowTimers.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
-
{{domxref("WindowTimers.clearTimeout()")}}
-
Cancels the delayed execution set using {{domxref("WindowTimers.setTimeout()")}}.
-
{{domxref("WindowTimers.setInterval()")}}
-
Schedules a function to execute every time a given number of milliseconds elapses.
-
{{domxref("WindowTimers.setTimeout()")}}
-
Schedules a function to execute in a given amount of time.
-
- -

規範

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

瀏覽器相容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

參見

- - -- cgit v1.2.3-54-g00ecf