+- {{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/png')")}}
+ - : Default setting. Creates a PNG image.
+- {{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/jpeg', quality)")}}
+ - : Creates a JPG image. Optionally, you can provide a quality in the range from 0 to 1, with one being the best quality and with 0 almost not recognizable but small in file size.
-
Once you have generated a data URI from you canvas, you are able to use it as the source of any {{HTMLElement("image")}} or put it into a hyper link with a download attribute to save it to disc, for example.
+Once you have generated a data URI from you canvas, you are able to use it as the source of any {{HTMLElement("image")}} or put it into a hyper link with a [download attribute](/zh-TW/docs/Web/HTML/Element/a#attr-download) to save it to disc, for example.
-
You can also create a {{domxref("Blob")}} from the canvas.
+- {{domxref("HTMLCanvasElement.toBlob", "canvas.toBlob(callback, type, encoderOptions)")}}
+ - : Creates a `Blob` object representing the image contained in the canvas.
-
+- {{domxref("ImageData")}}
+- [Manipulating video using canvas](/zh-TW/docs/Web/API/Canvas_API/Manipulating_video_using_canvas)
+- [Canvas, images and pixels – by Christian Heilmann](https://codepo8.github.io/canvas-images-and-pixels/)
-
{{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}
+{{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}
diff --git a/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.md b/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.md
index 81774802e93ef3..6619ee7412f777 100644
--- a/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.md
+++ b/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.md
@@ -3,34 +3,31 @@ title: 變形效果
slug: Web/API/Canvas_API/Tutorial/Transformations
translation_of: Web/API/Canvas_API/Tutorial/Transformations
---
-
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
+{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
-
+- 曾經套用過的變形效果,如 translate, rotate 和 scale(稍後說明)。
+- `strokeStyle`, `fillStyle`, `globalAlpha`, `lineWidth`, `lineCap`, `lineJoin`, `miterLimit`, `shadowOffsetX`, `shadowOffsetY`, `shadowBlur`, `shadowColor`, `globalCompositeOperation` 屬性的屬性值
+- 目前截圖路徑(稍後說明)。
-
{{EmbedLiveSample("A_save_and_restore_canvas_state_example", "180", "180", "https://mdn.mozillademos.org/files/249/Canvas_savestate.png")}}
+{{EmbedLiveSample("A_save_and_restore_canvas_state_example", "180", "180", "https://mdn.mozillademos.org/files/249/Canvas_savestate.png")}}
-
+![](canvas_grid_translate.png)第一個變形效果方法是 translate()。translate()是用來移動畫布,如右圖,原先畫布的原點在網格(0, 0)位置,我們可以移動畫布,使其原點移到(x, y)位置。
-
最好在做任何變形效果前先儲存一下畫布狀態,如此當我們需要復原先前的狀態時,只需要呼叫一下restore()即可,而且有一種情況是當我們在迴圈中移動畫布,如果不記得儲存和回復畫布狀態,繪圖區域很容易最後就超出邊界,然後出現圖案不見的狀況。
+最好在做任何變形效果前先儲存一下畫布狀態,如此當我們需要復原先前的狀態時,只需要呼叫一下 restore()即可,而且有一種情況是當我們在迴圈中移動畫布,如果不記得儲存和回復畫布狀態,繪圖區域很容易最後就超出邊界,然後出現圖案不見的狀況。
-
下面程式碼示範了利用translate()畫圖的好處,裡面,我們用了drawSpirograph()函數畫萬花筒類的圖案,如果沒有移動畫布原點,那麼每個圖案只會有四分之一會落在可視範圍,藉由移動畫布原點我們便可以自由變換每個圖案的位置,使圖案完整出現,而且省去手動計算調整每個圖案的座標位置。
+下面程式碼示範了利用 translate()畫圖的好處,裡面,我們用了 drawSpirograph()函數畫萬花筒類的圖案,如果沒有移動畫布原點,那麼每個圖案只會有四分之一會落在可視範圍,藉由移動畫布原點我們便可以自由變換每個圖案的位置,使圖案完整出現,而且省去手動計算調整每個圖案的座標位置。
-
{{EmbedLiveSample("A_translate_example", "330", "330", "https://mdn.mozillademos.org/files/256/Canvas_translate.png")}}
+{{EmbedLiveSample("A_translate_example", "330", "330", "https://mdn.mozillademos.org/files/256/Canvas_translate.png")}}
-
本範例我們呼叫rotate()方法來畫一系列環狀圖案。如果不用rotate(),同樣的效果也可以藉由個別計算x, y座標點(x = r*Math.cos(a); y = r*Math.sin(a))達成;呼叫rotate()和個別計算x, y座標點不同之處在於,個別計算x, y座標點只有旋轉圓形圓心,而圓形並沒有旋轉,呼叫rotate()則會旋轉圓形和圓心,不過因為我們的圖案是圓形,所以兩種作法產生的效果不會有差異。
+本範例我們呼叫 rotate()方法來畫一系列環狀圖案。如果不用 rotate(),同樣的效果也可以藉由個別計算 x, y 座標點(x = r\*Math.cos(a); y = r\*Math.sin(a))達成;呼叫 rotate()和個別計算 x, y 座標點不同之處在於,個別計算 x, y 座標點只有旋轉圓形圓心,而圓形並沒有旋轉,呼叫 rotate()則會旋轉圓形和圓心,不過因為我們的圖案是圓形,所以兩種作法產生的效果不會有差異。
-
我們執行了兩個迴圈來作圖,第一個迴圈決定的圓環個數和該圓環上圓環上圓點的個數的顏色,第二個迴圈決定了圓環上圓點的個數,每一次作圖前我們都儲存了原始畫布狀態,以便結束時可以復原狀態。畫布旋轉的弧度則以圓環上圓點的個數決定,像是最內圈的圓環共有六個圓點,所以每畫一個原點,畫布就旋轉60度(360度/6),第二的圓環有12個原點,所以畫布一次旋轉度數為30度(360度/12),以此類推。
+我們執行了兩個迴圈來作圖,第一個迴圈決定的圓環個數和該圓環上圓環上圓點的個數的顏色,第二個迴圈決定了圓環上圓點的個數,每一次作圖前我們都儲存了原始畫布狀態,以便結束時可以復原狀態。畫布旋轉的弧度則以圓環上圓點的個數決定,像是最內圈的圓環共有六個圓點,所以每畫一個原點,畫布就旋轉 60 度(360 度/6),第二的圓環有 12 個原點,所以畫布一次旋轉度數為 30 度(360 度/12),以此類推。
-
+- scale(x, y)
+ - : x 代表縮放畫布水平網格單位 x 倍,y 代表縮放畫布垂直網格單位 y 倍,輸入 1.0 不會造成縮放。如果輸入負值會造成座標軸鏡射,假設輸入 x 為-1,那麼原本畫布網格 X 軸上的正座標點都會變成負座標點、負座標點則變成正座標點。
-
只要利用scale(),我們可以建立著名的笛卡兒座標系;執行translate(0,canvas.height)先移動畫布原點到左下角,再執行scale(1,-1)顛倒Y軸正負值,一個笛卡兒座標系便完成了。
+只要利用 scale(),我們可以建立著名的笛卡兒座標系;執行 translate(0,canvas.height)先移動畫布原點到左下角,再執行 scale(1,-1)顛倒 Y 軸正負值,一個笛卡兒座標系便完成了。
-
+預設上畫布網格前進一單位等於前進一像素大小,所以縮小 0.5 倍,就會變成前進 0.5 的像素大小,亦即縮小圖像一半大小,反之,放大 2 倍將放大圖像 2 倍。
-
第一排第一個黃色圖案是沒有縮放的圖案,然後往右到了第二個圖案,我們程式碼中輸入了 (0.75, 0.75)的縮放倍率,到了第三個圖案,我們還是輸入了 (0.75, 0.75)的縮放倍率,而基於之前有縮小過一次,所以第三個圖案相對於第一個沒有縮放的圖案是0.75 × 0.75 = 0.5625倍。
+第一排第一個黃色圖案是沒有縮放的圖案,然後往右到了第二個圖案,我們程式碼中輸入了 (0.75, 0.75)的縮放倍率,到了第三個圖案,我們還是輸入了 (0.75, 0.75)的縮放倍率,而基於之前有縮小過一次,所以第三個圖案相對於第一個沒有縮放的圖案是 0.75 × 0.75 = 0.5625 倍。
-
+第二排藍色圖案我們只改變 Y 軸的縮放倍率,X 軸維持不變,因而產生一個比一個更扁的橢圓圖形。同理,第三排綠色圖案改變 X 軸的縮放倍率,Y 軸維持不變。
-
{{EmbedLiveSample("A_scale_example", "330", "330", "https://mdn.mozillademos.org/files/250/Canvas_scale.png")}}
+{{EmbedLiveSample("A_scale_example", "330", "330", "https://mdn.mozillademos.org/files/250/Canvas_scale.png")}}
-
最後一個方法是設定變形矩陣,藉由改變變形矩陣,我們因此可以營造各種變形效果;其實先前所提到的rotate, translate, scale都是在設定變形矩陣,而這邊的這個方法就是直接去改變變形矩陣。
+最後一個方法是設定變形矩陣,藉由改變變形矩陣,我們因此可以營造各種變形效果;其實先前所提到的 rotate, translate, scale 都是在設定變形矩陣,而這邊的這個方法就是直接去改變變形矩陣。
-
+- `transform(m11, m12, m21, m22, dx, dy)`
+ - : 呼叫 Transform 會拿目前的變形矩陣乘以下列矩陣:`plain m11 m21 dx m12 m22 dy 0 0 1 `運算後的新矩陣將取代目前的變形矩陣。其中 m11 代表水平縮放圖像,m12 代表水平偏移圖像,m21 代表垂直偏移圖像,m22 代表垂直縮放圖像,dx 代表水平移動圖像,dy 代表垂直移動圖像。如果輸入[`Infinity`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity) 值,不會引起例外錯誤,矩陣值會依照輸入設成無限。
+- `setTransform(m11, m12, m21, m22, dx, dy)`
+ - : 復原目前矩陣為恆等矩陣(Identiy matrix,也就是預設矩陣),然後再以輸入參數呼叫 transform()。
-
{{EmbedLiveSample("transform_.2F_setTransform_examples", "230", "280", "https://mdn.mozillademos.org/files/255/Canvas_transform.png")}}
+{{EmbedLiveSample("transform_.2F_setTransform_examples", "230", "280", "https://mdn.mozillademos.org/files/255/Canvas_transform.png")}}
-
{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors", "Web/Guide/HTML/Canvas_tutorial/Compositing")}}
+{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors", "Web/Guide/HTML/Canvas_tutorial/Compositing")}}
diff --git a/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.md b/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.md
index 426cb0dba0c587..35fb143da6f285 100644
--- a/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.md
+++ b/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.md
@@ -3,109 +3,93 @@ title: 使用影像
slug: Web/API/Canvas_API/Tutorial/Using_images
translation_of: Web/API/Canvas_API/Tutorial/Using_images
---
-
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations" )}}
+{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations" )}}
-
使用影像是{{HTMLElement("canvas")}}另一個有趣的功能,這個功能可以用來動態組合圖片或作為背景等等。任何瀏覽器支援的外部圖片格式都可以使用,例如PNG, GIF, 或JPEG,甚至也可以利用同一份頁面上其他畫布元素產生的影像.
+使用影像是{{HTMLElement("canvas")}}另一個有趣的功能,這個功能可以用來動態組合圖片或作為背景等等。任何瀏覽器支援的外部圖片格式都可以使用,例如 PNG, GIF, 或 JPEG,甚至也可以利用同一份頁面上其他畫布元素產生的影像.
-
+1. 取得{{domxref("HTMLImageElement")}}物件或其他畫布元素的參照(reference)作為來源,透過單純提供 URL 或圖片位置的方式是行不通的.
+2. 用 drawImage()函數在畫布上畫影像.
-
接下來便來看看要怎麼做.
+- {{domxref("HTMLImageElement")}}
+ - : 用 Image()建構成的影像或是{{HTMLElement("img")}}元素.
+- {{domxref("HTMLVideoElement")}}
+ - : 用{{domxref("HTMLVideoElement")}}元素作影像來源,抓取影片目前的影像畫格當作影像使用.
+- {{domxref("HTMLCanvasElement")}}
+ - : 用另一個{{domxref("HTMLCanvasElement")}}元素當影像來源.
+- {{domxref("ImageBitmap")}}
+ - : 可以被快速渲染的點陣圖(bitmap),點陣圖能由上述所有來源產生.
-
+這些來源統一參照 [CanvasImageSource](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#image-sources-for-2d-rendering-contexts)型態.
-
有好幾種方法能夠取得影像用於畫布.
+- 從{{domxref("document.images")}}
+- {{domxref("document.getElementsByTagName()")}}方法
+- 如果知道特定影像的 ID,那可以{{domxref("document.getElementById()")}}方法
-
+Using the [`crossOrigin`](/zh-TW/docs/HTML/CORS_settings_attributes) attribute on an 透過{{HTMLElement("HTMLImageElement")}}的[`crossOrigin`](/zh-TW/docs/HTML/CORS_settings_attributes)屬性, 我們可以要求從另一個網域載入影像來使用,若是寄存網域(thehosting domain)准許跨網路存取該影像,那麼我們便可以使用它而不用污染(taint)我們的畫布,反之,使用該影像會污染畫布([taint the canvas](/zh-TW/docs/HTML/CORS_Enabled_Image#What_is_a_.22tainted.22_canvas.3F))。
-
+如同取得其他影像,我們一樣能用{{domxref("document.getElementsByTagName()")}}或{{domxref("document.getElementById()")}}方法取得其他畫布元素,但是在使用之前請記得來源畫布上已經有繪上圖了。
-
如同取得其他影像,我們一樣能用{{domxref("document.getElementsByTagName()")}}或{{domxref("document.getElementById()")}}方法取得其他畫布元素,但是在使用之前請記得來源畫布上已經有繪上圖了。
使用其他畫布元素作為影像來源有很多有用的應用用途,其中之一便是建立第二個小畫布作為另一個大畫布的縮小影像.
上述程式碼執行後會載入影像.
若是只要載入一份影像,可以用上面的方法,不過當需要載入、追蹤多個影像時,我們就需要更好的方法了,雖然管理多個影像載入已經超出本教學的範疇,然而如果有興趣的話,可以參考JavaScript Image Preloader 這份文件.
+若是只要載入一份影像,可以用上面的方法,不過當需要載入、追蹤多個影像時,我們就需要更好的方法了,雖然管理多個影像載入已經超出本教學的範疇,然而如果有興趣的話,可以參考[JavaScript Image Preloader](http://www.webreference.com/programming/javascript/gr/column3/)這份文件.
-
+另一個載入影像的方法是利用[data: url](/zh-TW/docs/data_URIs),透過 data URL 可以直接將影像定義成 Base64 編碼的字串,然後嵌入程式碼之中.
-
+```js
+var img_src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
+```
-
+data URL 的好處之一是立即產生影像而不用再和伺服器連線,另一個好處是這樣便能夠將影像包入你的[CSS](/zh-TW/docs/Web/CSS), [JavaScript](/zh-TW/docs/Web/JavaScript), [HTML](/zh-TW/docs/Web/HTML)之中,讓影像更具可攜性.
-
壞處則是影像將不會被快取起來,而且對大影像來說編碼後的URL會很長.
我們還能夠使用{{HTMLElement("video")}}元素中的影片的影片畫格(縱使影片為隱藏),例如,現在我們有一個ID為”myvideo” 的{{HTMLElement("video")}}元素:
+我們還能夠使用{{HTMLElement("video")}}元素中的影片的影片畫格(縱使影片為隱藏),例如,現在我們有一個 ID 為”myvideo” 的{{HTMLElement("video")}}元素:
-
上面的方法會回傳一個{{domxref("HTMLVideoElement")}}的影像物件,如前所述,這個物件可以被視為CanvasImageSource類別的物件來使用。
- 關於如何利用<video>元素於畫布上的進階說明,可以參考html5Doctor的“video + canvas = magic ”一文.
+上面的方法會回傳一個{{domxref("HTMLVideoElement")}}的影像物件,如前所述,這個物件可以被視為 CanvasImageSource 類別的物件來使用。
+關於如何利用\
元素於畫布上的進階說明,可以參考 html5Doctor 的“[video + canvas = magic](http://html5doctor.com/video-canvas-magic/)”一文.
-影像繪圖
+## 影像繪圖
-一旦我們取得來源影像物件的參照(reference),便可以用drawImage()方法將影像渲染到畫布上,drawImage()方法是一個多載(overload)方法,有數個型態,待會我們會看到這項特性,現在我們先來看drawImage()最基本的型態:
+一旦我們取得來源影像物件的參照(reference),便可以用 drawImage()方法將影像渲染到畫布上,drawImage()方法是一個多載(overload)方法,有數個型態,待會我們會看到這項特性,現在我們先來看 drawImage()最基本的型態:
-
- drawImage(image , x , y )
- 從座標點(x, y)開始畫上image參數指定的來源影像(CanvasImageSource).
-
+- `drawImage(image, x, y)`
+ - : 從座標點(x, y)開始畫上 image 參數指定的來源影像(CanvasImageSource).
-範例: 一條簡單的線段影像
+### 範例: 一條簡單的線段影像
-這個範例會使用外部影像作為一個小型線圖的背景。利用預先劃好的圖作為背景的話就不用再靠程式來產生背景,如此一來可以顯著地減少程式碼。下面藉由影像物件的load事件處理器來處理繪圖作業,其中drawImage()方法把背景圖片放置在畫布左上角,座標點(0, 0)位置.
+這個範例會使用外部影像作為一個小型線圖的背景。利用預先劃好的圖作為背景的話就不用再靠程式來產生背景,如此一來可以顯著地減少程式碼。下面藉由影像物件的 load 事件處理器來處理繪圖作業,其中 drawImage()方法把背景圖片放置在畫布左上角,座標點(0, 0)位置.
-
-
<html>
- <body onload="draw();">
- <canvas id="canvas" width="180" height="150"></canvas>
- </body>
-</html>
-
-
+```html hidden
+
+
+
+
+
+```
-function draw() {
+```js
+function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
@@ -153,88 +135,82 @@ img.src = 'myImage.png'; // Set source path
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
-}
+}
+```
-結果如下:
+結果如下:
-{{EmbedLiveSample("Example.3A_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}
+{{EmbedLiveSample("Example.3A_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}
-縮放
+## 縮放
-drawImage()的第二個型態增加了兩個新參數,讓我們在畫布上放置影像的同時並縮放影像.
+drawImage()的第二個型態增加了兩個新參數,讓我們在畫布上放置影像的同時並縮放影像.
-
- drawImage(image , x , y , width , height )
- 當放置影像於畫布上時,會按照參數width(寬)、height(高)來縮放影像.
-
+- `drawImage(image, x, y, width, height)`
+ - : 當放置影像於畫布上時,會按照參數 width(寬)、height(高)來縮放影像.
-範例: 排列影像
+### 範例: 排列影像
-本例我們會取一張影像作為桌布,然後透過簡單的迴圈來重複縮放、貼上影像於畫布上。在程式碼中,第一個迴圈走一遍每一列,第二個迴圈走一遍每一行,影像則縮小成原始影像的三分之一,50 x 38像素.
+本例我們會取一張影像作為桌布,然後透過簡單的迴圈來重複縮放、貼上影像於畫布上。在程式碼中,第一個迴圈走一遍每一列,第二個迴圈走一遍每一行,影像則縮小成原始影像的三分之一,50 x 38 像素.
-
-
Note : 過度縮放影像可能會造成影像模糊或產生顆粒感,所以如果影像中有文字需要閱讀,最好不要縮放影像.
-
+> **備註:** 過度縮放影像可能會造成影像模糊或產生顆粒感,所以如果影像中有文字需要閱讀,最好不要縮放影像.
-
-
<html>
- <body onload="draw();">
- <canvas id="canvas" width="150" height="150"></canvas>
- </body>
-</html>
-
-
+```html hidden
+
+
+
+
+
+```
-function draw() {
+```js
+function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
- for (var i=0;i<4;i++){
- for (var j=0;j<3;j++){
+ for (var i=0;i<4;i++){
+ for (var j=0;j<3;j++){
ctx.drawImage(img,j*50,i*38,50,38);
}
}
};
img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
-}
-
-結果如下:
-
-{{EmbedLiveSample("Example.3A_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}
+}
+```
-切割影像
+結果如下:
-drawImage()第三個型態接受9個參數,其中8個讓我們從原始影像中切出一部分影像、縮放並畫到畫布上.
+{{EmbedLiveSample("Example.3A_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}
-
- drawImage(image , sx , sy , sWidth , sHeight , dx , dy , dWidth , dHeight )
- image參數是來源影像物件,(sx, sy)代表在來源影像中以(sx, sy)座標點作為切割的起始點,sWidth和sHeight代表切割寬和高,(dx, dy)代表放到畫布上的座標點,dWidth和dHeight代表縮放影像至指定的寬和高.
-
+## 切割影像
- 請參照右圖,前四個參數定義了在來源影像上切割的起始點和切割大小,後四個參數定義了畫到畫布上的位置和影像大小.
+drawImage()第三個型態接受 9 個參數,其中 8 個讓我們從原始影像中切出一部分影像、縮放並畫到畫布上.
-切割是一個很有用的工具,我們可以把所有影像放到一張影像上,然後利用切割來組成最終完整的影像,比如說,我們可以把所有需要用來組成一張圖表的文字放到一張PNG圖檔內,之後只需要單純地再依據資料來縮放圖表,另外,我們也不用多次載入多張影像,這樣對提升載入影像效能頗有幫助.
+- `drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)`
+ - : image 參數是來源影像物件,(sx, sy)代表在來源影像中以(sx, sy)座標點作為切割的起始點,sWidth 和 sHeight 代表切割寬和高,(dx, dy)代表放到畫布上的座標點,dWidth 和 dHeight 代表縮放影像至指定的寬和高.
-
+![](canvas_drawimage.jpg)請參照右圖,前四個參數定義了在來源影像上切割的起始點和切割大小,後四個參數定義了畫到畫布上的位置和影像大小.
-
+切割是一個很有用的工具,我們可以把所有影像放到一張影像上,然後利用切割來組成最終完整的影像,比如說,我們可以把所有需要用來組成一張圖表的文字放到一張 PNG 圖檔內,之後只需要單純地再依據資料來縮放圖表,另外,我們也不用多次載入多張影像,這樣對提升載入影像效能頗有幫助.
-範例: 畫一個有畫框的影像
+### 範例: 畫一個有畫框的影像
-本例用和前一個範例一樣的犀牛圖,然後切出犀牛頭部影像部分再放入一個影像畫框,這個影像畫框是一個有陰影的24位元PNG圖檔,因為24位元PNG影像具備完整的8位元不透明色版(alpha channel),所以不像GIF影像和8位元PNG影像,它能夠放任何背景之上而無須擔心產生消光色(matte color).
+本例用和前一個範例一樣的犀牛圖,然後切出犀牛頭部影像部分再放入一個影像畫框,這個影像畫框是一個有陰影的 24 位元 PNG 圖檔,因為 24 位元 PNG 影像具備完整的 8 位元不透明色版(alpha channel),所以不像 GIF 影像和 8 位元 PNG 影像,它能夠放任何背景之上而無須擔心產生消光色(matte color).
-<html>
- <body onload="draw();">
- <canvas id="canvas" width="150" height="150"></canvas>
- <div style="display:none;">
- <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
- <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
- </div>
- </body>
-</html>
-
+```html
+
+
+
+
+
+
+
+
+
+```
-function draw() {
+```js
+function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
@@ -244,46 +220,49 @@ img.src = 'myImage.png'; // Set source path
// Draw frame
ctx.drawImage(document.getElementById('frame'),0,0);
-}
+}
+```
-這次我們不產生新的{{domxref("HTMLImageElement")}}物件,改採用直接把影像包入HTML的{{HTMLElement("img")}}標籤,然後再取得影像元素,其中HTML上的影像已經透過設定CSS屬性{{cssxref("display")}}為none來隱藏起來了.
+這次我們不產生新的{{domxref("HTMLImageElement")}}物件,改採用直接把影像包入 HTML 的{{HTMLElement("img")}}標籤,然後再取得影像元素,其中 HTML 上的影像已經透過設定 CSS 屬性{{cssxref("display")}}為 none 來隱藏起來了.
-{{EmbedLiveSample("Example.3A_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}
+{{EmbedLiveSample("Example.3A_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}
-程式碼相當簡單,每個{{HTMLElement("img")}}有自己的ID屬性,這樣便可以利用{{domxref("document.getElementById()")}}輕易取得,之後再簡單地用drawImage()方法切割犀牛影像然後縮放並放到畫布上,最後第二個drawImage()再把畫框放到上面.
+程式碼相當簡單,每個{{HTMLElement("img")}}有自己的 ID 屬性,這樣便可以利用{{domxref("document.getElementById()")}}輕易取得,之後再簡單地用 drawImage()方法切割犀牛影像然後縮放並放到畫布上,最後第二個 drawImage()再把畫框放到上面.
-畫廊範例
+## 畫廊範例
-在本章的最後一個範例,我們將建造一個小畫廊。當網頁載入完成時,我們會為每一張影像產生一個{{HTMLElement("canvas")}}元素,並且加上畫框.
+在本章的最後一個範例,我們將建造一個小畫廊。當網頁載入完成時,我們會為每一張影像產生一個{{HTMLElement("canvas")}}元素,並且加上畫框.
-本範例中,每一張影像的寬高是固定的,畫框也是一樣,你可以嘗試看看改進程式碼,依據影像的寬高來設定畫框,使畫框能剛剛好框住影像.
+本範例中,每一張影像的寬高是固定的,畫框也是一樣,你可以嘗試看看改進程式碼,依據影像的寬高來設定畫框,使畫框能剛剛好框住影像.
-從下方的程式碼範例可以很清楚看到,我們為{{domxref("document.images")}}容器內的影像,一張一張地新建畫布,其中,對於不熟悉文件物件模型 (DOM)的人來說,大慨比較值得注意之處在於使用到{{domxref("Node.insertBefore")}} 方法;insertBefore()是影像元素的父節點(亦即<td>元素)的一個方法,這個方法會把新畫布元素插入於影像元素之前.
+從下方的程式碼範例可以很清楚看到,我們為{{domxref("document.images")}}容器內的影像,一張一張地新建畫布,其中,對於不熟悉文件物件模型 (DOM)的人來說,大慨比較值得注意之處在於使用到{{domxref("Node.insertBefore")}} 方法;insertBefore()是影像元素的父節點(亦即\元素)的一個方法,這個方法會把新畫布元素插入於影像元素之前.
-<html>
- <body onload="draw();">
- <table>
- <tr>
- <td><img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"></td>
- </tr>
- <tr>
- <td><img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"></td>
- <td><img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"></td>
- </tr>
- </table>
- <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
- </body>
-</html>
-
+```html
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
-這些是一些設定樣式的CSS:
+這些是一些設定樣式的 CSS:
-body {
+```css
+body {
background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A;
margin: 10px;
}
@@ -299,14 +278,15 @@ table {
td {
padding: 15px;
}
-
+```
-綜合起來這就是建造出我們小畫廊的程式碼:
+綜合起來這就是建造出我們小畫廊的程式碼:
-function draw() {
+```js
+function draw() {
// Loop through all images
- for (var i=0;i<document.images.length;i++){
+ for (var i=0;i
+}
+```
-{{EmbedLiveSample("Art_gallery_example", 725, 400, "https://mdn.mozillademos.org/files/205/Canvas_art_gallery.jpg")}}
+{{EmbedLiveSample("Art_gallery_example", 725, 400, "https://mdn.mozillademos.org/files/205/Canvas_art_gallery.jpg")}}
-控制影像縮放行為
+## 控制影像縮放行為
-如前所述,縮放影像會導致影像模糊化或是顆粒化,你可以嘗試透過繪圖環境的imageSmoothingEnabled屬性來控制影像平滑演算法的使用,預設上這個屬性的值為true,也就是說當縮放時,影像會經過平滑處理。如果要關掉這個功能,你可以這麼做:
+如前所述,縮放影像會導致影像模糊化或是顆粒化,你可以嘗試透過繪圖環境的 imageSmoothingEnabled 屬性來控制影像平滑演算法的使用,預設上這個屬性的值為 true,也就是說當縮放時,影像會經過平滑處理。如果要關掉這個功能,你可以這麼做:
-ctx.mozImageSmoothingEnabled = false;
-
+```js
+ctx.mozImageSmoothingEnabled = false;
+```
-{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Drawing_shapes", "Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors")}}
+{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Drawing_shapes", "Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors")}}
diff --git a/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.md b/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.md
index 115d56cc77cfa4..ab065e7e66e45f 100644
--- a/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.md
+++ b/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.md
@@ -3,46 +3,47 @@ title: CanvasRenderingContext2D.clearRect()
slug: Web/API/CanvasRenderingContext2D/clearRect
translation_of: Web/API/CanvasRenderingContext2D/clearRect
---
-{{APIRef}}
+{{APIRef}}
-Canvas 2D API 的 CanvasRenderingContext2D
.clearRect()
方法可以設定指定矩形(經由坐標 (x, y) 及大小 (width, height) )範圍內的所有像素為透明,清除所有先前繪製的內容。
+Canvas 2D API 的 **`CanvasRenderingContext2D.clearRect()`** 方法可以設定指定矩形(經由坐標 _(x, y)_ 及大小 _(width, height)_)範圍內的所有像素為透明,清除所有先前繪製的內容。
-語法
+## 語法
-void ctx .clearRect(x, y, width, height);
-
+```plain
+void ctx.clearRect(x, y, width, height);
+```
-參數
+### 參數
-
- x
- The x axis of the coordinate for the rectangle starting point.
- y
- The y axis of the coordinate for the rectangle starting point.
- width
- The rectangle's width.
- height
- The rectangle's height.
-
+- `x`
+ - : The x axis of the coordinate for the rectangle starting point.
+- `y`
+ - : The y axis of the coordinate for the rectangle starting point.
+- `width`
+ - : The rectangle's width.
+- `height`
+ - : The rectangle's height.
-Usage notes
+## Usage notes
-A common problem with clearRect
is that it may appear it does not work when not using paths properly . Don't forget to call {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} before starting to draw the new frame after calling clearRect
.
+A common problem with `clearRect` is that it may appear it does not work when not [using paths properly](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#Drawing_paths). Don't forget to call {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} before starting to draw the new frame after calling `clearRect`.
-範例
+## 範例
-Using the clearRect
method
+### Using the `clearRect` method
-This is just a simple code snippet which uses the clearRect
method.
+This is just a simple code snippet which uses the `clearRect` method.
-HTML
+#### HTML
-<canvas id="canvas"></canvas>
-
+```html
+
+```
-JavaScript
+#### JavaScript
-var canvas = document.getElementById('canvas');
+```js
+var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
@@ -56,19 +57,17 @@ ctx.clearRect(10, 10, 100, 100);
// clear the whole canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);
-
+```
-Edit the code below and see your changes update live in the canvas:
+Edit the code below and see your changes update live in the canvas:
-
+```
-{{ EmbedLiveSample('Playable_code', 700, 400) }}
+{{ EmbedLiveSample('Playable_code', 700, 400) }}
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.CanvasRenderingContext2D.clearRect")}}
-參見
+## 參見
-
- The interface defining it, {{domxref("CanvasRenderingContext2D")}}
- {{domxref("CanvasRenderingContext2D.fillRect()")}}
- {{domxref("CanvasRenderingContext2D.strokeRect()")}}
-
+- The interface defining it, {{domxref("CanvasRenderingContext2D")}}
+- {{domxref("CanvasRenderingContext2D.fillRect()")}}
+- {{domxref("CanvasRenderingContext2D.strokeRect()")}}
diff --git a/files/zh-tw/web/api/canvasrenderingcontext2d/index.md b/files/zh-tw/web/api/canvasrenderingcontext2d/index.md
index 9b7fdecc188cd7..c4399dd3363599 100644
--- a/files/zh-tw/web/api/canvasrenderingcontext2d/index.md
+++ b/files/zh-tw/web/api/canvasrenderingcontext2d/index.md
@@ -3,371 +3,321 @@ title: CanvasRenderingContext2D
slug: Web/API/CanvasRenderingContext2D
translation_of: Web/API/CanvasRenderingContext2D
---
-{{APIRef}}
+{{APIRef}}**CanvasRenderingContext2D** 介面被使用於繪製矩形、文字、影像以及其它基於 canvas 元素的物件。此介面提供了繪製 {{ HTMLElement("canvas") }} 元素外觀的 2D 渲染環境。
-CanvasRenderingContext2D 介面被使用於繪製矩形、文字、影像以及其它基於 canvas 元素的物件。此介面提供了繪製 {{ HTMLElement("canvas") }} 元素外觀的 2D 渲染環境。
+要取得此實作此介面的實體物件,可以於一個 `` 元素上以 "2d" 為參數呼叫 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 方法:
-要取得此實作此介面的實體物件,可以於一個 <canvas>
元素上以 "2d" 為參數呼叫 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 方法:
-
-var canvas = document.getElementById('mycanvas'); // in your HTML this element appears as <canvas id="mycanvas"></canvas>
+```js
+var canvas = document.getElementById('mycanvas'); // in your HTML this element appears as
var ctx = canvas.getContext('2d');
-
+```
-只要你有了 canvas 的 2D 繪製背景物件,你就可以在其中繪圖。 舉個例子:
+只要你有了 canvas 的 2D 繪製背景物件,你就可以在其中繪圖。 舉個例子:
-ctx.fillStyle = "rgb(200,0,0)"; // sets the color to fill in the rectangle with
+```js
+ctx.fillStyle = "rgb(200,0,0)"; // sets the color to fill in the rectangle with
ctx.fillRect(10, 10, 55, 50); // draws the rectangle at position 10, 10 with a width of 55 and a height of 50
-
-
-canvas 教學 有更多資訊、範例,以及資源。
-
-繪製矩形
-
-有三個函式可以馬上在點陣圖上畫出長方形。
-
-
- {{domxref("CanvasRenderingContext2D.clearRect()")}}
- Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.
- {{domxref("CanvasRenderingContext2D.fillRect()")}}
- Draws a filled rectangle at (x, y) position whose size is determined by width and height .
- {{domxref("CanvasRenderingContext2D.strokeRect()")}}
- Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style.
-
-
-繪製文字
-
-The following methods are provided for drawing text. See also the {{domxref("TextMetrics")}} object for text properties.
-
-
- {{domxref("CanvasRenderingContext2D.fillText()")}}
- Draws (fills) a given text at the given (x,y) position.
- {{domxref("CanvasRenderingContext2D.strokeText()")}}
- Draws (strokes) a given text at the given (x, y) position.
- {{domxref("CanvasRenderingContext2D.measureText()")}}
- Returns a {{domxref("TextMetrics")}} object.
-
-
-線條樣式
-
-The following methods and properties control how lines are drawn.
-
-
- {{domxref("CanvasRenderingContext2D.lineWidth")}}
- Width of lines. Default 1.0
- {{domxref("CanvasRenderingContext2D.lineCap")}}
- Type of endings on the end of lines. Possible values: butt
(default), round
, square
.
- {{domxref("CanvasRenderingContext2D.lineJoin")}}
- Defines the type of corners where two lines meet. Possible values: round
, bevel
, miter
(default).
- {{domxref("CanvasRenderingContext2D.miterLimit")}}
- Miter limit ratio. Default 10
.
- {{domxref("CanvasRenderingContext2D.getLineDash()")}}
- Returns the current line dash pattern array containing an even number of non-negative numbers.
- {{domxref("CanvasRenderingContext2D.setLineDash()")}}
- Sets the current line dash pattern.
- {{domxref("CanvasRenderingContext2D.lineDashOffset")}}
- Specifies where to start a dash array on a line.
-
-
-文字樣式
-
-The following properties control how text is laid out.
-
-
- {{domxref("CanvasRenderingContext2D.font")}}
- Font setting. Default value 10px sans-serif
.
- {{domxref("CanvasRenderingContext2D.textAlign")}}
- Text alignment setting. Possible values: start
(default), end
, left
, right
or center
.
- {{domxref("CanvasRenderingContext2D.textBaseline")}}
- Baseline alignment setting. Possible values: top
, hanging
, middle
, alphabetic
(default), ideographic
, bottom
.
- {{domxref("CanvasRenderingContext2D.direction")}}
- Directionality. Possible values: ltr, rtl
, inherit
(default).
-
-
-填充及邊線樣式
-
-Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.
-
-
- {{domxref("CanvasRenderingContext2D.fillStyle")}}
- Color or style to use inside shapes. Default #000
(black).
- {{domxref("CanvasRenderingContext2D.strokeStyle")}}
- Color or style to use for the lines around shapes. Default #000
(black).
-
-
-漸層填色及圖案填充
-
-
- {{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
- Creates a linear gradient along the line given by the coordinates represented by the parameters.
- {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
- Creates a radial gradient given by the coordinates of the two circles represented by the parameters.
- {{domxref("CanvasRenderingContext2D.createPattern()")}}
- Creates a pattern using the specified image (a {{domxref("CanvasImageSource")}}). It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.
-
-
-陰影
-
-
- {{domxref("CanvasRenderingContext2D.shadowBlur")}}
- Specifies the blurring effect. Default 0
- {{domxref("CanvasRenderingContext2D.shadowColor")}}
- Color of the shadow. Default fully-transparent black.
- {{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
- Horizontal distance the shadow will be offset. Default 0.
- {{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
- Vertical distance the shadow will be offset. Default 0.
-
-
-路徑
-
-The following methods can be used to manipulate paths of objects.
-
-
- {{domxref("CanvasRenderingContext2D.beginPath()")}}
- Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
- {{domxref("CanvasRenderingContext2D.closePath()")}}
- Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
- {{domxref("CanvasRenderingContext2D.moveTo()")}}
- Moves the starting point of a new sub-path to the (x, y) coordinates.
- {{domxref("CanvasRenderingContext2D.lineTo()")}}
- Connects the last point in the subpath to the x, y
coordinates with a straight line.
- {{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
- Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo()
before creating the Bézier curve.
- {{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
- Adds a quadratic Bézier curve to the current path.
- {{domxref("CanvasRenderingContext2D.arc()")}}
- Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
- {{domxref("CanvasRenderingContext2D.arcTo()")}}
- Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
- {{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
- Adds an ellipse to the path which is centered at (x, y) position with the radii radiusX and radiusY starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
- {{domxref("CanvasRenderingContext2D.rect()")}}
- Creates a path for a rectangle at position (x, y) with a size that is determined by width and height .
-
-
-繪製路徑
-
-
- {{domxref("CanvasRenderingContext2D.fill()")}}
- Fills the subpaths with the current fill style.
- {{domxref("CanvasRenderingContext2D.stroke()")}}
- Strokes the subpaths with the current stroke style.
- {{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
- If a given element is focused, this method draws a focus ring around the current path.
- {{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
- Scrolls the current path or a given path into the view.
- {{domxref("CanvasRenderingContext2D.clip()")}}
- Creates a clipping path from the current sub-paths. Everything drawn after clip()
is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.
- {{domxref("CanvasRenderingContext2D.isPointInPath()")}}
- Reports whether or not the specified point is contained in the current path.
- {{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
- Reports whether or not the specified point is inside the area contained by the stroking of a path.
-
-
-變形
-
-Objects in the CanvasRenderingContext2D
rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.
-
-
- {{domxref("CanvasRenderingContext2D.currentTransform")}}
- Current transformation matrix ({{domxref("SVGMatrix")}} object).
- {{domxref("CanvasRenderingContext2D.rotate()")}}
- Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
- {{domxref("CanvasRenderingContext2D.scale()")}}
- Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
- {{domxref("CanvasRenderingContext2D.translate()")}}
- Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
- {{domxref("CanvasRenderingContext2D.transform()")}}
- Multiplies the current transformation matrix with the matrix described by its arguments.
- {{domxref("CanvasRenderingContext2D.setTransform()")}}
- Resets the current transform to the identity matrix, and then invokes the transform()
method with the same arguments.
- {{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
- Resets the current transform by the identity matrix.
-
-
-合成
-
-
- {{domxref("CanvasRenderingContext2D.globalAlpha")}}
- Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0
(opaque).
- {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
- With globalAlpha
applied this sets how shapes and images are drawn onto the existing bitmap.
-
-
-繪製圖形
-
-
- {{domxref("CanvasRenderingContext2D.drawImage()")}}
- Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
-
-
-像素控制
-
-See also the {{domxref("ImageData")}} object.
-
-
- {{domxref("CanvasRenderingContext2D.createImageData()")}}
- Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
- {{domxref("CanvasRenderingContext2D.getImageData()")}}
- Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.
- {{domxref("CanvasRenderingContext2D.putImageData()")}}
- Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
-
-
-圖像平滑
-
-
- {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
- Image smoothing mode; if disabled, images will not be smoothed if scaled.
-
-
-canvas 狀態
-
-The CanvasRenderingContext2D
rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:
-
-
- {{domxref("CanvasRenderingContext2D.save()")}}
- Saves the current drawing style state using a stack so you can revert any change you make to it using restore()
.
- {{domxref("CanvasRenderingContext2D.restore()")}}
- Restores the drawing style state to the last element on the 'state stack' saved by save()
.
- {{domxref("CanvasRenderingContext2D.canvas")}}
- A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
-
-
-點擊區域
-
-
- {{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
- Adds a hit region to the canvas.
- {{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
- Removes the hit region with the specified id
from the canvas.
- {{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
- Removes all hit regions from the canvas.
-
-
-非標準 API
-
-Blink 及 WebKit 引擎
-
-Most of these APIs are deprecated and will be removed in the future .
-
-
- {{non-standard_inline}} CanvasRenderingContext2D.clearShadow()
- Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
- {{non-standard_inline}} CanvasRenderingContext2D.drawImageFromRect()
- This is redundant with an equivalent overload of drawImage
.
- {{non-standard_inline}} CanvasRenderingContext2D.setAlpha()
- Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setCompositeOperation()
- Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setLineWidth()
- Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setLineJoin()
- Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setLineCap()
- Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setMiterLimit()
- Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setStrokeColor()
- Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setFillColor()
- Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.setShadow()
- Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.webkitLineDash
- Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.webkitLineDashOffset
- Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
- {{non-standard_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
- Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.
-
-
-Blink 引擎專屬
-
-
- {{non-standard_inline}} CanvasRenderingContext2D.getContextAttributes()
- Inspired by the same WebGLRenderingContext
method it returns an Canvas2DContextAttributes
object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true
by default) to indicate that transparency is used in the canvas.
- {{non-standard_inline}} CanvasRenderingContext2D.isContextLost()
- Inspired by the same WebGLRenderingContext
method it returns true
if the Canvas context has been lost, or false
if not.
-
-
-WebKit 引擎專屬
-
-
- {{non-standard_inline}} CanvasRenderingContext2D.webkitBackingStorePixelRatio
- The backing store size in relation to the canvas element. See High DPI Canvas .
- {{non-standard_inline}} CanvasRenderingContext2D.webkitGetImageDataHD
- Intended for HD backing stores, but removed from canvas specifications.
- {{non-standard_inline}} CanvasRenderingContext2D.webkitPutImageDataHD
- Intended for HD backing stores, but removed from canvas specifications.
-
-
-Gecko 引擎專屬
-
-
- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
- CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
-
-
-Prefixed APIs
-
-
- {{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransform
- Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}.
- {{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransformInverse
- Sets or gets the current inversed transformation matrix.
- {{non-standard_inline}} CanvasRenderingContext2D.mozImageSmoothingEnabled
- See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
- {{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDash
- An array which specifies the lengths of alternating dashes and gaps. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
- {{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDashOffset
- Specifies where to start a dash array on a line. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
- {{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozTextStyle
- Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.
- {{non-standard_inline}} {{Deprecated_Inline}} CanvasRenderingContext2D.mozDrawText()
- This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.
- {{non-standard_inline}} {{Deprecated_Inline}} CanvasRenderingContext2D.mozMeasureText()
- This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.
- {{non-standard_inline}} {{Deprecated_Inline}} CanvasRenderingContext2D.mozPathText()
- This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
- {{non-standard_inline}} {{Deprecated_Inline}} CanvasRenderingContext2D.mozTextAlongPath()
- This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
-
-
-Internal APIs (chrome-context only)
-
-
- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
- Renders a region of a XUL element into the canvas
.
- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
- Renders a region of a window into the canvas
. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
- {{non-standard_inline}} CanvasRenderingContext2D.demote()
- This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
-
-
-Internet Explorer
-
-
- {{non-standard_inline}} CanvasRenderingContext2D.msFillRule
- The fill rule to use. This must be one of evenodd
or nonzero
(default).
-
-
-規範
+```
+
+[canvas 教學](/zh-TW/docs/Web/API/Canvas_API/Tutorial)有更多資訊、範例,以及資源。
+
+## 繪製矩形
+
+有三個函式可以馬上在點陣圖上畫出長方形。
+
+- {{domxref("CanvasRenderingContext2D.clearRect()")}}
+ - : Sets all pixels in the rectangle defined by starting point _(x, y)_ and size _(width, height)_ to transparent black, erasing any previously drawn content.
+- {{domxref("CanvasRenderingContext2D.fillRect()")}}
+ - : Draws a filled rectangle at _(x, y)_ position whose size is determined by _width_ and _height_.
+- {{domxref("CanvasRenderingContext2D.strokeRect()")}}
+ - : Paints a rectangle which has a starting point at _(x, y)_ and has a _w_ width and an _h_ height onto the canvas, using the current stroke style.
+
+## 繪製文字
+
+The following methods are provided for drawing text. See also the {{domxref("TextMetrics")}} object for text properties.
+
+- {{domxref("CanvasRenderingContext2D.fillText()")}}
+ - : Draws (fills) a given text at the given (x,y) position.
+- {{domxref("CanvasRenderingContext2D.strokeText()")}}
+ - : Draws (strokes) a given text at the given _(x, y)_ position.
+- {{domxref("CanvasRenderingContext2D.measureText()")}}
+ - : Returns a {{domxref("TextMetrics")}} object.
+
+## 線條樣式
+
+The following methods and properties control how lines are drawn.
+
+- {{domxref("CanvasRenderingContext2D.lineWidth")}}
+ - : Width of lines. Default `1.0`
+- {{domxref("CanvasRenderingContext2D.lineCap")}}
+ - : Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`.
+- {{domxref("CanvasRenderingContext2D.lineJoin")}}
+ - : Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default).
+- {{domxref("CanvasRenderingContext2D.miterLimit")}}
+ - : Miter limit ratio. Default `10`.
+- {{domxref("CanvasRenderingContext2D.getLineDash()")}}
+ - : Returns the current line dash pattern array containing an even number of non-negative numbers.
+- {{domxref("CanvasRenderingContext2D.setLineDash()")}}
+ - : Sets the current line dash pattern.
+- {{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+ - : Specifies where to start a dash array on a line.
+
+## 文字樣式
+
+The following properties control how text is laid out.
+
+- {{domxref("CanvasRenderingContext2D.font")}}
+ - : Font setting. Default value `10px sans-serif`.
+- {{domxref("CanvasRenderingContext2D.textAlign")}}
+ - : Text alignment setting. Possible values: `start` (default), `end`, `left`, `right` or `center`.
+- {{domxref("CanvasRenderingContext2D.textBaseline")}}
+ - : Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`.
+- {{domxref("CanvasRenderingContext2D.direction")}}
+ - : Directionality. Possible values: `ltr, rtl`, `inherit` (default).
+
+## 填充及邊線樣式
+
+Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.
+
+- {{domxref("CanvasRenderingContext2D.fillStyle")}}
+ - : Color or style to use inside shapes. Default `#000` (black).
+- {{domxref("CanvasRenderingContext2D.strokeStyle")}}
+ - : Color or style to use for the lines around shapes. Default `#000` (black).
+
+## 漸層填色及圖案填充
+
+- {{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+ - : Creates a linear gradient along the line given by the coordinates represented by the parameters.
+- {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+ - : Creates a radial gradient given by the coordinates of the two circles represented by the parameters.
+- {{domxref("CanvasRenderingContext2D.createPattern()")}}
+ - : Creates a pattern using the specified image (a {{domxref("CanvasImageSource")}}). It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.
+
+## 陰影
+
+- {{domxref("CanvasRenderingContext2D.shadowBlur")}}
+ - : Specifies the blurring effect. Default `0`
+- {{domxref("CanvasRenderingContext2D.shadowColor")}}
+ - : Color of the shadow. Default fully-transparent black.
+- {{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+ - : Horizontal distance the shadow will be offset. Default 0.
+- {{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+ - : Vertical distance the shadow will be offset. Default 0.
+
+## 路徑
+
+The following methods can be used to manipulate paths of objects.
+
+- {{domxref("CanvasRenderingContext2D.beginPath()")}}
+ - : Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
+- {{domxref("CanvasRenderingContext2D.closePath()")}}
+ - : Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
+- {{domxref("CanvasRenderingContext2D.moveTo()")}}
+ - : Moves the starting point of a new sub-path to the **(x, y)** coordinates.
+- {{domxref("CanvasRenderingContext2D.lineTo()")}}
+ - : Connects the last point in the subpath to the `x, y` coordinates with a straight line.
+- {{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+ - : Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using `moveTo()` before creating the Bézier curve.
+- {{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+ - : Adds a quadratic Bézier curve to the current path.
+- {{domxref("CanvasRenderingContext2D.arc()")}}
+ - : Adds an arc to the path which is centered at _(x, y)_ position with radius _r_ starting at _startAngle_ and ending at _endAngle_ going in the given direction by _anticlockwise_ (defaulting to clockwise).
+- {{domxref("CanvasRenderingContext2D.arcTo()")}}
+ - : Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
+- {{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
+ - : Adds an ellipse to the path which is centered at _(x, y)_ position with the radii _radiusX_ and _radiusY_ starting at _startAngle_ and ending at _endAngle_ going in the given direction by _anticlockwise_ (defaulting to clockwise).
+- {{domxref("CanvasRenderingContext2D.rect()")}}
+ - : Creates a path for a rectangle at _position (x, y)_ with a size that is determined by _width_ and _height_.
+
+## 繪製路徑
+
+- {{domxref("CanvasRenderingContext2D.fill()")}}
+ - : Fills the subpaths with the current fill style.
+- {{domxref("CanvasRenderingContext2D.stroke()")}}
+ - : Strokes the subpaths with the current stroke style.
+- {{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+ - : If a given element is focused, this method draws a focus ring around the current path.
+- {{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+ - : Scrolls the current path or a given path into the view.
+- {{domxref("CanvasRenderingContext2D.clip()")}}
+ - : Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see [Clipping paths](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Compositing) in the Canvas tutorial.
+- {{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+ - : Reports whether or not the specified point is contained in the current path.
+- {{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+ - : Reports whether or not the specified point is inside the area contained by the stroking of a path.
+
+## 變形
+
+Objects in the `CanvasRenderingContext2D` rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.
+
+- {{domxref("CanvasRenderingContext2D.currentTransform")}}
+ - : Current transformation matrix ({{domxref("SVGMatrix")}} object).
+- {{domxref("CanvasRenderingContext2D.rotate()")}}
+ - : Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
+- {{domxref("CanvasRenderingContext2D.scale()")}}
+ - : Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
+- {{domxref("CanvasRenderingContext2D.translate()")}}
+ - : Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
+- {{domxref("CanvasRenderingContext2D.transform()")}}
+ - : Multiplies the current transformation matrix with the matrix described by its arguments.
+- {{domxref("CanvasRenderingContext2D.setTransform()")}}
+ - : Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments.
+- {{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+ - : Resets the current transform by the identity matrix.
+
+## 合成
+
+- {{domxref("CanvasRenderingContext2D.globalAlpha")}}
+ - : Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque).
+- {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+ - : With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap.
+
+## 繪製圖形
+
+- {{domxref("CanvasRenderingContext2D.drawImage()")}}
+ - : Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
+
+## 像素控制
+
+See also the {{domxref("ImageData")}} object.
+
+- {{domxref("CanvasRenderingContext2D.createImageData()")}}
+ - : Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
+- {{domxref("CanvasRenderingContext2D.getImageData()")}}
+ - : Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at _(sx, sy)_ and has an _sw_ width and _sh_ height.
+- {{domxref("CanvasRenderingContext2D.putImageData()")}}
+ - : Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
+
+## 圖像平滑
+
+- {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+ - : Image smoothing mode; if disabled, images will not be smoothed if scaled.
+
+## canvas 狀態
+
+The `CanvasRenderingContext2D` rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:
+
+- {{domxref("CanvasRenderingContext2D.save()")}}
+ - : Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`.
+- {{domxref("CanvasRenderingContext2D.restore()")}}
+ - : Restores the drawing style state to the last element on the 'state stack' saved by `save()`.
+- {{domxref("CanvasRenderingContext2D.canvas")}}
+ - : A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
+## 點擊區域
+
+- {{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+ - : Adds a hit region to the canvas.
+- {{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+ - : Removes the hit region with the specified `id` from the canvas.
+- {{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+ - : Removes all hit regions from the canvas.
+
+## 非標準 API
+
+### Blink 及 WebKit 引擎
+
+Most of these APIs are [deprecated and will be removed in the future](https://code.google.com/p/chromium/issues/detail?id=363198).
+
+- {{non-standard_inline}} `CanvasRenderingContext2D.clearShadow()`
+ - : Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+- {{non-standard_inline}} `CanvasRenderingContext2D.drawImageFromRect()`
+ - : This is redundant with an equivalent overload of `drawImage`.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setAlpha()`
+ - : Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setCompositeOperation()`
+ - : Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setLineWidth()`
+ - : Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setLineJoin()`
+ - : Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setLineCap()`
+ - : Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setMiterLimit()`
+ - : Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setStrokeColor()`
+ - : Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setFillColor()`
+ - : Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.setShadow()`
+ - : Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitLineDash`
+ - : Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitLineDashOffset`
+ - : Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitImageSmoothingEnabled`
+ - : Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.
+
+### Blink 引擎專屬
+
+- {{non-standard_inline}} `CanvasRenderingContext2D.getContextAttributes()`
+ - : Inspired by the same `WebGLRenderingContext` method it returns an `Canvas2DContextAttributes` object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (`true` by default) to indicate that transparency is used in the canvas.
+- {{non-standard_inline}} `CanvasRenderingContext2D.isContextLost()`
+ - : Inspired by the same `WebGLRenderingContext` method it returns `true` if the Canvas context has been lost, or `false` if not.
+
+### WebKit 引擎專屬
+
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitBackingStorePixelRatio`
+ - : The backing store size in relation to the canvas element. See [High DPI Canvas](http://www.html5rocks.com/en/tutorials/canvas/hidpi/).
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitGetImageDataHD`
+ - : Intended for HD backing stores, but removed from canvas specifications.
+- {{non-standard_inline}} `CanvasRenderingContext2D.webkitPutImageDataHD`
+ - : Intended for HD backing stores, but removed from canvas specifications.
+
+### Gecko 引擎專屬
+
+- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+ - : CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
+
+#### Prefixed APIs
+
+- {{non-standard_inline}} `CanvasRenderingContext2D.mozCurrentTransform`
+ - : Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}.
+- {{non-standard_inline}} `CanvasRenderingContext2D.mozCurrentTransformInverse`
+ - : Sets or gets the current inversed transformation matrix.
+- {{non-standard_inline}} `CanvasRenderingContext2D.mozImageSmoothingEnabled`
+ - : See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
+- {{non-standard_inline}} {{deprecated_inline}} `CanvasRenderingContext2D.mozDash`
+ - : An array which specifies the lengths of alternating dashes and gaps. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+- {{non-standard_inline}} {{deprecated_inline}} `CanvasRenderingContext2D.mozDashOffset`
+ - : Specifies where to start a dash array on a line. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+- {{non-standard_inline}} {{deprecated_inline}} `CanvasRenderingContext2D.mozTextStyle`
+ - : Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.
+- {{non-standard_inline}} {{Deprecated_Inline}} `CanvasRenderingContext2D.mozDrawText()`
+ - : This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.
+- {{non-standard_inline}} {{Deprecated_Inline}} `CanvasRenderingContext2D.mozMeasureText()`
+ - : This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.
+- {{non-standard_inline}} {{Deprecated_Inline}} `CanvasRenderingContext2D.mozPathText()`
+ - : This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+- {{non-standard_inline}} {{Deprecated_Inline}} `CanvasRenderingContext2D.mozTextAlongPath()`
+ - : This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
+#### Internal APIs (chrome-context only)
+
+- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
+ - : Renders a region of a XUL element into the `canvas`.
+- {{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
+ - : Renders a region of a window into the `canvas`. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
+- {{non-standard_inline}} `CanvasRenderingContext2D.demote()`
+ - : This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
+
+### Internet Explorer
+
+- {{non-standard_inline}} `CanvasRenderingContext2D.msFillRule`
+ - : The [fill rule](http://cairographics.org/manual/cairo-cairo-t.html#cairo-fill-rule-t) to use. This must be one of `evenodd` or `nonzero` (default).
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.CanvasRenderingContext2D")}}
-相容性註記
+## 相容性註記
-
- Starting with Gecko 5.0 {{geckoRelease("5.0")}}, specifying invalid values are now silently ignored for the following methods and properties: translate()
, transform()
, rotate(),
scale(),
rect()
, clearRect()
, fillRect()
, strokeRect()
, lineTo()
, moveTo()
, quadraticCurveTo()
, arc()
, shadowOffsetX
, shadowOffsetY
, shadowBlur
.
-
+- Starting with Gecko 5.0 {{geckoRelease("5.0")}}, specifying invalid values are now silently ignored for the following methods and properties: `translate()`, `transform()`, ` rotate(), ``scale(),` `rect()`, `clearRect()`, `fillRect()`, `strokeRect()`, `lineTo()`, `moveTo()`, `quadraticCurveTo()`, `arc()`, `shadowOffsetX`, `shadowOffsetY`, `shadowBlur`.
-參見
+## 參見
-
- {{domxref("HTMLCanvasElement")}}
-
+- {{domxref("HTMLCanvasElement")}}
diff --git a/files/zh-tw/web/api/closeevent/index.md b/files/zh-tw/web/api/closeevent/index.md
index db00421b16b4c2..acadca7a962754 100644
--- a/files/zh-tw/web/api/closeevent/index.md
+++ b/files/zh-tw/web/api/closeevent/index.md
@@ -6,93 +6,39 @@ tags:
translation_of: Web/API/CloseEvent
original_slug: WebSockets/WebSockets_reference/CloseEvent
---
-當 WebSocket 連線關閉時,客戶端會收到一個 CloseEvent
,由 WebSocket
物件 onclose
屬性表示的監聽器接收。
-屬性
-
-
-
-
-
-
-
-
- code
- unsigned long
- WebSocket 伺服器給予的連線關閉代碼。「狀態代碼」列有所有可能值。
-
-
- reason
- {{ domxref("DOMString") }}
- 表示伺服器關閉連線的原因,這因不同的伺服器與子協定而定。
-
-
- wasClean
- boolean
- 表示連線關閉情況是否乾淨。
-
-
-
-狀態代碼
-以下列有所有合法的狀態代碼。
-
-
-
-
-
-
-
- 0-999
- 尚未使用的保留值。
-
-
- 1000
- 正常關閉,連線成功地達到建立時的目標。
-
-
- 1001
- 端點去離,伺服器故障或是瀏覽器從開啟連線的頁面離去的情形。
-
-
- 1002
- 因協定錯誤造成連線被端點消滅。
-
-
- 1003
- 因端點接收不能處理的資料形態(舉例來說,文字端點收到二進制資料)而消滅連線。
-
-
- 1004
- 端點收到過大的資料幀而消滅連線。
-
-
- 1005
- 保留值。 表示意外地未給予狀態代碼的情形。
-
-
- 1006
- 保留值。 用以表示在預期收到狀態代碼的情形下不正常(即未送關閉幀)的連線關閉。
-
-
- 1007-1999
- 保留以作為未來的 WebSocket 標準之用。
-
-
- 2000-2999
- 保留以作為 WebSocket 擴展之用。
-
-
- 3000-3999
- 程式庫與框架使用的值,應用程式可不 使用。
-
-
- 4000-4999
- 應用程式使用的值。
-
-
-
-參見
-
-瀏覽器兼容
+當 WebSocket 連線關閉時,客戶端會收到一個 `CloseEvent`,由 `WebSocket` 物件 `onclose` 屬性表示的監聽器接收。
+
+## 屬性
+
+| 屬性 | 形態 | 描述 |
+| ---------- | ------------------------------------ | ---------------------------------------------------------------- |
+| `code` | [`unsigned long`](/en/unsigned_long) | WebSocket 伺服器給予的連線關閉代碼。「狀態代碼」列有所有可能值。 |
+| `reason` | {{ domxref("DOMString") }} | 表示伺服器關閉連線的原因,這因不同的伺服器與子協定而定。 |
+| `wasClean` | `boolean` | 表示連線關閉情況是否乾淨。 |
+
+## 狀態代碼
+
+以下列有所有合法的狀態代碼。
+
+| 狀態代碼 | 描述 |
+| --------- | -------------------------------------------------------------------------------- |
+| 0-999 | **尚未使用的保留值。** |
+| 1000 | 正常關閉,連線成功地達到建立時的目標。 |
+| 1001 | 端點去離,伺服器故障或是瀏覽器從開啟連線的頁面離去的情形。 |
+| 1002 | 因協定錯誤造成連線被端點消滅。 |
+| 1003 | 因端點接收不能處理的資料形態(舉例來說,文字端點收到二進制資料)而消滅連線。 |
+| 1004 | 端點收到過大的資料幀而消滅連線。 |
+| 1005 | **保留值。**表示意外地未給予狀態代碼的情形。 |
+| 1006 | **保留值。**用以表示在預期收到狀態代碼的情形下不正常(即未送關閉幀)的連線關閉。 |
+| 1007-1999 | **保留以作為未來的 WebSocket 標準之用。** |
+| 2000-2999 | **保留以作為 WebSocket 擴展之用。** |
+| 3000-3999 | 程式庫與框架使用的值,應用程式**可不**使用。 |
+| 4000-4999 | 應用程式使用的值。 |
+
+## 參見
+
+- [`WebSocket`](/zh_tw/WebSockets/WebSockets_reference/WebSocket)
+
+## 瀏覽器兼容
+
{{Compat("api.CloseEvent")}}
diff --git a/files/zh-tw/web/api/console/assert/index.md b/files/zh-tw/web/api/console/assert/index.md
index 13f7661edeeb19..3872a4f5377e41 100644
--- a/files/zh-tw/web/api/console/assert/index.md
+++ b/files/zh-tw/web/api/console/assert/index.md
@@ -11,45 +11,41 @@ tags:
- 網頁開發
translation_of: Web/API/console/assert
---
-{{APIRef("Console API")}}
+{{APIRef("Console API")}}
-如果斷言(assertion)為非(false),主控台會顯示錯誤訊息;如果斷言為是(true),則不發生任何事。
+如果斷言(assertion)為非(false),主控台會顯示錯誤訊息;如果斷言為是(true),則不發生任何事。
-{{AvailableInWorkers}}
+{{AvailableInWorkers}}
-
-
注意 :在 Node.js 內 console.assert()
方法的實做,與瀏覽器並不相同。
+> **備註:** 在 Node.js 內 `console.assert()` 方法的實做,與瀏覽器並不相同。瀏覽器內呼叫 falsy 的 `console.assert()` 斷言出現 `message`,但不會中斷程式碼的執行。然而在 Node.js 裡面,falsy 斷言會拋出 `AssertionError` 錯誤。
-
瀏覽器內呼叫 falsy 的 console.assert()
斷言出現 message
,但不會中斷程式碼的執行。然而在 Node.js 裡面,falsy 斷言會拋出 AssertionError
錯誤。
-
+## 語法
-語法
+```plain
+console.assert(assertion, obj1 [, obj2, ..., objN]);
+console.assert(assertion, msg [, subst1, ..., substN]); // c-like message formatting
+```
-console.assert(assertion , obj1 [, obj2 , ..., objN ]);
-console.assert(assertion , msg [, subst1 , ..., substN ]); // c-like message formatting
-
+### 參數
-參數
+- `assertion`
+ - : 布林表達式。如果斷言為非,訊息會出現在主控台上。
+- `obj1` ... `objN`
+ - : 要印出來的 JavaScript 物件名單。 The string representations of each of these objects are appended together in the order listed and output.
+- `msg`
+ - : 包含零個以上的 JavaScript 替代(substitution)字串。
+- `subst1` ... `substN`
+ - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output.
-
- assertion
- 布林表達式。如果斷言為非,訊息會出現在主控台上。
- obj1
... objN
- 要印出來的 JavaScript 物件名單。 The string representations of each of these objects are appended together in the order listed and output.
- msg
- 包含零個以上的 JavaScript 替代(substitution)字串。
- subst1
... substN
- JavaScript objects with which to replace substitution strings within msg
. This parameter gives you additional control over the format of the output.
-
+請參見 {{domxref("console")}} 的 [Outputting text to the console](/zh-TW/docs/Web/API/console#Outputting_text_to_the_console) 以獲取詳細資訊。
-請參見 {{domxref("console")}} 的 Outputting text to the console 以獲取詳細資訊。
+## 範例
-範例
+以下程式碼示範一個 JavaScript 物件的斷言使用:
-以下程式碼示範一個 JavaScript 物件的斷言使用:
-
-const errorMsg = 'the # is not even';
-for (let number = 2; number <= 5; number += 1) {
+```js
+const errorMsg = 'the # is not even';
+for (let number = 2; number <= 5; number += 1) {
console.log('the # is ' + number);
console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
// or, using ES2015 object property shorthand:
@@ -62,40 +58,40 @@ for (let number = 2; number <= 5; number += 1) {
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}
-
+```
-請注意,雖然包含替換字符串的字符串在 Node 中用作 console.log
的參數,但很多(如果不是大多數)瀏覽器...
+請注意,雖然包含替換字符串的字符串在 Node 中用作 `console.log` 的參數,但很多(如果不是大多數)瀏覽器...
-console.log('the word is %s', 'foo');
+```js
+console.log('the word is %s', 'foo');
// output: the word is foo
-
+```
-...在所有瀏覽器中,使用此類字符串目前無法作為console.assert的參數使用:
+...在所有瀏覽器中,使用此類字符串目前無法作為 console.assert 的參數使用:
-console.assert(false, 'the word is %s', 'foo');
+```js
+console.assert(false, 'the word is %s', 'foo');
// correct output in Node (e.g. v8.10.0) and some browsers
// (e.g. Firefox v60.0.2):
// Assertion failed: the word is foo
// incorrect output in some browsers
// (e.g. Chrome v67.0.3396.87):
// Assertion failed: the word is %s foo
-
+```
-有關詳細信息,請參閱 {{domxref("console")}} 文檔中的將文本輸出到控制台 。
+有關詳細信息,請參閱 {{domxref("console")}} 文檔中的[將文本輸出到控制台](/zh-TW/docs/Web/API/console#Outputting_text_to_the_console)。
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
-{{Compat}}
+{{Compat}}
-參見
+## 參見
-
+- [WHATWG Console Standard: console.assert](https://console.spec.whatwg.org/#assert-condition-data)
+- [Opera Dragonfly documentation: Console](http://www.opera.com/dragonfly/documentation/console/)
+- [MSDN: Using the F12 Tools Console to View Errors and Status](http://msdn.microsoft.com/library/gg589530)
+- [Chrome Developer Tools: Using the Console](https://developer.chrome.com/devtools/docs/console#assertions)
diff --git a/files/zh-tw/web/api/console/index.md b/files/zh-tw/web/api/console/index.md
index f5a021ceeab1e0..baee34ff04a7b1 100644
--- a/files/zh-tw/web/api/console/index.md
+++ b/files/zh-tw/web/api/console/index.md
@@ -13,174 +13,159 @@ tags:
- web console
translation_of: Web/API/Console
---
-{{APIRef("Console API")}}
-
-The Console
object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.
-
-The Console
object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console
. For example:
-
-console.log("Failed to open the specified link")
-
-This page documents the Methods available on the Console
object and gives a few Usage examples.
-
-{{AvailableInWorkers}}
-
-Methods
-
-
- {{domxref("Console.assert()")}}
- Log a message and stack trace to console if the first argument is false
.
- {{domxref("Console.clear()")}}
- Clear the console.
- {{domxref("Console.count()")}}
- Log the number of times this line has been called with the given label.
- {{domxref("Console.debug()")}}
- An alias for log()
.
- Note : Starting with Chromium 58 this method only appears in Chromium browser consoles when level "Verbose" is selected.
-
- {{domxref("Console.dir()")}} {{Non-standard_inline}}
- Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
- {{domxref("Console.dirxml()")}} {{Non-standard_inline}}
-
- Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
-
- {{domxref("Console.error()")}}
- Outputs an error message. You may use string substitution and additional arguments with this method.
- {{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
- An alias for error()
.
- {{domxref("Console.group()")}}
- Creates a new inline group , indenting all following output by another level. To move back out a level, call groupEnd()
.
- {{domxref("Console.groupCollapsed()")}}
- Creates a new inline group , indenting all following output by another level. However, unlike group()
this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd()
.
- {{domxref("Console.groupEnd()")}}
- Exits the current inline group .
- {{domxref("Console.info()")}}
- Informative logging of information. You may use string substitution and additional arguments with this method.
- {{domxref("Console.log()")}}
- For general output of logging information. You may use string substitution and additional arguments with this method.
- {{domxref("Console.profile()")}} {{Non-standard_inline}}
- Starts the browser's built-in profiler (for example, the Firefox performance tool ). You can specify an optional name for the profile.
- {{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
- Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool ).
- {{domxref("Console.table()")}}
- Displays tabular data as a table.
- {{domxref("Console.time()")}}
- Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
- {{domxref("Console.timeEnd()")}}
- Stops the specified timer and logs the elapsed time in seconds since it started.
- {{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
- Adds a marker to the browser's Timeline or Waterfall tool.
- {{domxref("Console.trace()")}}
- Outputs a stack trace .
- {{domxref("Console.warn()")}}
- Outputs a warning message. You may use string substitution and additional arguments with this method.
-
-
-Usage
-
-Outputting text to the console
-
-The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods respectively. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.
-
-There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.
-
-Outputting a single object
-
-The simplest way to use the logging methods is to output a single object:
-
-var someObject = { str: "Some text", id: 5 };
+{{APIRef("Console API")}}
+
+The **`Console`** object provides access to the browser's debugging console (e.g. the [Web Console](/zh-TW/docs/Tools/Web_Console) in Firefox). The specifics of how it works varies from browser to browser, but there is a _de facto_ set of features that are typically provided.
+
+The `Console` object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply `console`. For example:
+
+```js
+console.log("Failed to open the specified link")
+```
+
+This page documents the [Methods](#methods) available on the `Console` object and gives a few [Usage](#usage) examples.
+
+{{AvailableInWorkers}}
+
+## Methods
+
+- {{domxref("Console.assert()")}}
+ - : Log a message and stack trace to console if the first argument is `false`.
+- {{domxref("Console.clear()")}}
+ - : Clear the console.
+- {{domxref("Console.count()")}}
+ - : Log the number of times this line has been called with the given label.
+- {{domxref("Console.debug()")}}
+ - : An alias for `log()`.
+
+ > **備註:** Starting with Chromium 58 this method only appears in Chromium browser consoles when level "Verbose" is selected.
+- {{domxref("Console.dir()")}} {{Non-standard_inline}}
+ - : Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+- {{domxref("Console.dirxml()")}} {{Non-standard_inline}}
+ - : Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
+- {{domxref("Console.error()")}}
+ - : Outputs an error message. You may use [string substitution](/zh-TW/docs/Web/API/console#Using_string_substitutions) and additional arguments with this method.
+- {{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+ - : An alias for `error()`.
+- {{domxref("Console.group()")}}
+ - : Creates a new inline [group](/zh-TW/docs/Web/API/console#Using_groups_in_the_console), indenting all following output by another level. To move back out a level, call `groupEnd()`.
+- {{domxref("Console.groupCollapsed()")}}
+ - : Creates a new inline [group](/zh-TW/docs/Web/API/console#Using_groups_in_the_console), indenting all following output by another level. However, unlike `group()` this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call `groupEnd()`.
+- {{domxref("Console.groupEnd()")}}
+ - : Exits the current inline [group](/zh-TW/docs/Web/API/console#Using_groups_in_the_console).
+- {{domxref("Console.info()")}}
+ - : Informative logging of information. You may use [string substitution](/zh-TW/docs/Web/API/console#Using_string_substitutions) and additional arguments with this method.
+- {{domxref("Console.log()")}}
+ - : For general output of logging information. You may use [string substitution](/zh-TW/docs/Web/API/console#Using_string_substitutions) and additional arguments with this method.
+- {{domxref("Console.profile()")}} {{Non-standard_inline}}
+ - : Starts the browser's built-in profiler (for example, the [Firefox performance tool](/zh-TW/docs/Tools/Performance)). You can specify an optional name for the profile.
+- {{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+ - : Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the [Firefox performance tool](/zh-TW/docs/Tools/Performance)).
+- {{domxref("Console.table()")}}
+ - : Displays tabular data as a table.
+- {{domxref("Console.time()")}}
+ - : Starts a [timer](/zh-TW/docs/Web/API/console#Timers) with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+- {{domxref("Console.timeEnd()")}}
+ - : Stops the specified [timer](/zh-TW/docs/Web/API/console#Timers) and logs the elapsed time in seconds since it started.
+- {{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+ - : Adds a marker to the browser's [Timeline](https://developer.chrome.com/devtools/docs/timeline) or [Waterfall](/zh-TW/docs/Tools/Performance/Waterfall) tool.
+- {{domxref("Console.trace()")}}
+ - : Outputs a [stack trace](/zh-TW/docs/Web/API/console#Stack_traces).
+- {{domxref("Console.warn()")}}
+ - : Outputs a warning message. You may use [string substitution](/zh-TW/docs/Web/API/console#Using_string_substitutions) and additional arguments with this method.
+
+## Usage
+
+### Outputting text to the console
+
+The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods respectively. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.
+
+There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.
+
+#### Outputting a single object
+
+The simplest way to use the logging methods is to output a single object:
+
+```js
+var someObject = { str: "Some text", id: 5 };
console.log(someObject);
-
+```
-The output looks something like this:
+The output looks something like this:
-[09:27:13.475] ({str:"Some text", id:5})
+```plain
+[09:27:13.475] ({str:"Some text", id:5})
+```
-Outputting multiple objects
+#### Outputting multiple objects
-You can also output multiple objects by simply listing them when calling the logging method, like this:
+You can also output multiple objects by simply listing them when calling the logging method, like this:
-var car = "Dodge Charger";
+```js
+var car = "Dodge Charger";
var someObject = { str: "Some text", id: 5 };
-console.info("My first car was a", car, ". The object is:", someObject);
-
-This output will look like this:
-
-[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
-
-
-Using string substitutions
-
-Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:
-
-
-
-
-
-
-
-
- %o or %O
- Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
-
-
- %d or %i
- Outputs an integer. Number formatting is supported, for example console.log("Foo %.2d", 1.1)
will output the number as two significant figures with a leading 0: Foo 01
-
-
- %s
- Outputs a string.
-
-
- %f
- Outputs a floating-point value. Formatting is supported, for example console.log("Foo %.2f", 1.1)
will output the number to 2 decimal places: Foo 1.10
-
-
-
-
-
-
Note : Precision formatting doesn't work in Chrome
-
-
-Each of these pulls the next argument after the format string off the parameter list. For example:
-
-for (var i=0; i<5; i++) {
+console.info("My first car was a", car, ". The object is:", someObject);
+```
+
+This output will look like this:
+
+```plain
+[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+```
+
+#### Using string substitutions
+
+Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:
+
+| Substitution string | Description |
+| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| %o or %O | Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector. |
+| %d or %i | Outputs an integer. Number formatting is supported, for example `console.log("Foo %.2d", 1.1)` will output the number as two significant figures with a leading 0: `Foo 01` |
+| %s | Outputs a string. |
+| %f | Outputs a floating-point value. Formatting is supported, for example `console.log("Foo %.2f", 1.1)` will output the number to 2 decimal places: `Foo 1.10` |
+
+> **備註:** Precision formatting doesn't work in Chrome
+
+Each of these pulls the next argument after the format string off the parameter list. For example:
+
+```plain
+for (var i=0; i<5; i++) {
console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
}
-
+```
-The output looks like this:
+The output looks like this:
-[13:14:13.481] Hello, Bob. You've called me 1 times.
+```plain
+[13:14:13.481] Hello, Bob. You've called me 1 times.
[13:14:13.483] Hello, Bob. You've called me 2 times.
[13:14:13.485] Hello, Bob. You've called me 3 times.
[13:14:13.487] Hello, Bob. You've called me 4 times.
[13:14:13.488] Hello, Bob. You've called me 5 times.
-
-
-Styling console output
+```
-You can use the %c
directive to apply a CSS style to console output:
+#### Styling console output
-console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+You can use the `%c` directive to apply a CSS style to console output:
-The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+```js
+console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+```
-
+The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.![](css-styling.png)
-
-
Note : Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.
-
+> **備註:** Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.
-Using groups in the console
+### Using groups in the console
-You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group()
. The console.groupCollapsed()
method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
+You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
-Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed()
method is the same as group()
at this time.
+> **備註:** Collapsed groups are not supported yet in Gecko; the `groupCollapsed()` method is the same as `group()` at this time.
-To exit the current group, simply call console.groupEnd()
. For example, given this code:
+To exit the current group, simply call `console.groupEnd()`. For example, given this code:
-console.log("This is the outer level");
+```js
+console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
@@ -190,36 +175,38 @@ console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.debug("Back to the outer level");
-
+```
-The output looks like this:
+The output looks like this:
-
+![nesting.png](/@api/deki/files/6082/=nesting.png)
-Timers
+### Timers
-In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console
object. To start a timer, call the console.time
()
method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd()
method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.
+In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the `console` object. To start a timer, call the ` console.time``() ` method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the `console.timeEnd()` method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.
-For example, given this code:
+For example, given this code:
-console.time("answer time");
+```js
+console.time("answer time");
alert("Click to continue");
console.timeEnd("answer time");
-
+```
-Will log the time needed by the user to discard the alert box:
+Will log the time needed by the user to discard the alert box:
-
+![timerresult.png](/@api/deki/files/6084/=timerresult.png)
-Notice that the timer's name is displayed both when the timer is started and when it's stopped.
+Notice that the timer's name is displayed both when the timer is started and when it's stopped.
-Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+> **備註:** It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
-Stack traces
+### Stack traces
-The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:
+The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:
-function foo() {
+```js
+function foo() {
function bar() {
console.trace();
}
@@ -227,42 +214,36 @@ console.timeEnd("answer time");
}
foo();
-
+```
-The output in the console looks something like this:
+The output in the console looks something like this:
-
+![](api-trace2.png)
-Specifications
+## Specifications
-{{Specifications}}
+{{Specifications}}
-Browser compatibility
+## Browser compatibility
-{{Compat}}
+{{Compat}}
-Notes
+## Notes
-
- At least in Firefox, if a page defines a console
object, that object overrides the one built into Firefox.
- Prior to {{Gecko("12.0")}}, the console object's methods only work when the Web Console is open. Starting with {{Gecko("12.0")}}, output is cached until the Web Console is opened, then displayed at that time.
- It's worth noting that the Firefox's built-in Console
object is compatible with the one provided by Firebug .
-
+- At least in Firefox, if a page defines a `console` object, that object overrides the one built into Firefox.
+- Prior to {{Gecko("12.0")}}, the console object's methods only work when the Web Console is open. Starting with {{Gecko("12.0")}}, output is cached until the Web Console is opened, then displayed at that time.
+- It's worth noting that the Firefox's built-in `Console` object is compatible with the one provided by [Firebug](http://getfirebug.com/).
-See also
+## See also
-
+- [Tools](/zh-TW/docs/Tools)
+- [Web Console](/zh-TW/docs/Tools/Web_Console) — how the Web Console in Firefox handles console API calls
+- [Remote debugging](/zh-TW/docs/Tools/Remote_Debugging) — how to see console output when the debugging target is a mobile device
+- [On-device console logging](/zh-TW/docs/Mozilla/Firefox_OS/Debugging/On-device_console_logging) — how to do logging on Firefox OS devices
-Other implementations
+### Other implementations
-
+- [Google Chrome DevTools](https://developers.google.com/chrome-developer-tools/docs/console-api)
+- [Firebug](http://getfirebug.com/wiki/index.php/Console_API)
+- [Internet Explorer]()
+- [Safari](https://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)
diff --git a/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.md b/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.md
index 8cd61e07bed9a8..4f346e67097876 100644
--- a/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.md
+++ b/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.md
@@ -3,31 +3,29 @@ title: Determining the dimensions of elements
slug: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements
translation_of: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements
---
-{{APIRef("CSSOM View")}}
+{{APIRef("CSSOM View")}}
-There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use width
and
height ;
or, the overriding min-width
and max-width
, and min-height
and max-height
properties.
+There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use `width `and` ``height;` or, the overriding [`min-width`](/zh-TW/docs/Web/CSS/min-width) and [`max-width`](/zh-TW/docs/Web/CSS/max-width), and [`min-height`](/zh-TW/docs/Web/CSS/min-height) and [`max-height`](/zh-TW/docs/Web/CSS/max-height) properties.
-How much room does it use up?
+## How much room does it use up?
-If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the offsetWidth
and offsetHeight
properties. Most of the time these are the same as width and height of getBoundingClientRect()
, when there aren't any transforms applied to the element. In case of transforms, the offsetWidth
and offsetHeight
returns the element's layout width and height, while getBoundingClientRect()
returns the rendering width and height. As an example, if the element has width: 100px;
and transform: scale(0.5);
the getBoundingClientRect()
will return 50 as the width, while offsetWidth
will return 100.
+If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the [`offsetWidth`](/en/DOM/element.offsetWidth) and [`offsetHeight`](/en/DOM/element.offsetHeight) properties. Most of the time these are the same as width and height of [`getBoundingClientRect()`](/en/DOM/element.getBoundingClientRect), when there aren't any transforms applied to the element. In case of transforms, the `offsetWidth` and `offsetHeight` returns the element's layout width and height, while `getBoundingClientRect()` returns the rendering width and height. As an example, if the element has `width: 100px;` and `transform: scale(0.5);` the `getBoundingClientRect()` will return 50 as the width, while `offsetWidth` will return 100.
-
+![Image:Dimensions-offset.png](/@api/deki/files/186/=Dimensions-offset.png)
-What's the size of the displayed content?
+## What's the size of the displayed content?
-If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the clientWidth
and clientHeight
properties:
+If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the [`clientWidth`](/en/DOM/element.clientWidth) and [`clientHeight`](/en/DOM/element.clientHeight) properties:
-
+![Image:Dimensions-client.png](/@api/deki/files/185/=Dimensions-client.png)
-How big is the content?
+## How big is the content?
-If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the scrollWidth
and scrollHeight
properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.
+If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the [`scrollWidth`](/en/DOM/element.scrollWidth) and [`scrollHeight`](/en-US/docs/Web/API/Element.scrollHeight) properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.
-For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, scrollWidth
will return 600 while scrollHeight
will return 400.
+For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, `scrollWidth` will return 600 while `scrollHeight` will return 400.
-參見
+## 參見
-
+-
+- [MSDN: Measuring Element Dimension and Location]()
diff --git a/files/zh-tw/web/api/css_object_model/index.md b/files/zh-tw/web/api/css_object_model/index.md
index dbbf1848a75a9c..3c9f380a20e246 100644
--- a/files/zh-tw/web/api/css_object_model/index.md
+++ b/files/zh-tw/web/api/css_object_model/index.md
@@ -9,63 +9,59 @@ tags:
- TopicStub
translation_of: Web/API/CSS_Object_Model
---
-{{DefaultAPISidebar('CSSOM')}}
+{{DefaultAPISidebar('CSSOM')}}
-The CSS Object Model is a set of APIs allowing to manipulate CSS from JavaScript. It is the pendant of DOM and HTML APIs, but for CSS. It allows to read and modify CSS style dynamically.
+The **CSS Object Model** is a set of APIs allowing to manipulate CSS from JavaScript. It is the pendant of DOM and HTML APIs, but for CSS. It allows to read and modify CSS style dynamically.
-Reference
+## Reference
-
- {{domxref("AnimationEvent")}}
- {{domxref("CaretPosition")}}
- {{domxref("CSS")}}
- {{domxref("CSSCharsetRule")}}
- {{domxref("CSSConditionRule")}}
- {{domxref("CSSCounterStyleRule")}}
- {{domxref("CSSFontFaceRule")}}
- {{domxref("CSSFontFeatureValuesMap")}}
- {{domxref("CSSFontFeatureValuesRule")}}
- {{domxref("CSSGroupingRule")}}
- {{domxref("CSSImportRule")}}
- {{domxref("CSSKeyframeRule")}}
- {{domxref("CSSKeyframesRule")}}
- {{domxref("CSSMarginRule")}}
- {{domxref("CSSMediaRule")}}
- {{domxref("CSSNamespaceRule")}}
- {{domxref("CSSPageRule")}}
- {{domxref("CSSRule")}}
- {{domxref("CSSRuleList")}}
- {{domxref("CSSStyleSheet")}}
- {{domxref("CSSStyleDeclaration")}}
- {{domxref("CSSSupportsRule")}}
- {{domxref("CSSVariablesMap")}}
- {{domxref("CSSViewportRule")}}
- {{domxref("ElementCSSInlineStyle")}}
- {{domxref("GeometryUtils")}}
- {{domxref("GetStyleUtils")}}
- {{domxref("LinkStyle")}}
- {{domxref("MediaList")}}
- {{domxref("MediaQueryList")}}
- {{domxref("PseudoElement")}}
- {{domxref("Screen")}}
- {{domxref("StyleSheet")}}
- {{domxref("StyleSheetList")}}
- {{domxref("TransitionEvent")}}
-
+- {{domxref("AnimationEvent")}}
+- {{domxref("CaretPosition")}}
+- {{domxref("CSS")}}
+- {{domxref("CSSCharsetRule")}}
+- {{domxref("CSSConditionRule")}}
+- {{domxref("CSSCounterStyleRule")}}
+- {{domxref("CSSFontFaceRule")}}
+- {{domxref("CSSFontFeatureValuesMap")}}
+- {{domxref("CSSFontFeatureValuesRule")}}
+- {{domxref("CSSGroupingRule")}}
+- {{domxref("CSSImportRule")}}
+- {{domxref("CSSKeyframeRule")}}
+- {{domxref("CSSKeyframesRule")}}
+- {{domxref("CSSMarginRule")}}
+- {{domxref("CSSMediaRule")}}
+- {{domxref("CSSNamespaceRule")}}
+- {{domxref("CSSPageRule")}}
+- {{domxref("CSSRule")}}
+- {{domxref("CSSRuleList")}}
+- {{domxref("CSSStyleSheet")}}
+- {{domxref("CSSStyleDeclaration")}}
+- {{domxref("CSSSupportsRule")}}
+- {{domxref("CSSVariablesMap")}}
+- {{domxref("CSSViewportRule")}}
+- {{domxref("ElementCSSInlineStyle")}}
+- {{domxref("GeometryUtils")}}
+- {{domxref("GetStyleUtils")}}
+- {{domxref("LinkStyle")}}
+- {{domxref("MediaList")}}
+- {{domxref("MediaQueryList")}}
+- {{domxref("PseudoElement")}}
+- {{domxref("Screen")}}
+- {{domxref("StyleSheet")}}
+- {{domxref("StyleSheetList")}}
+- {{domxref("TransitionEvent")}}
-Several other interfaces are also extended by the CSSOM-related specifications: {{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.
+Several other interfaces are also extended by the CSSOM-related specifications: {{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.
-Tutorials
+## Tutorials
-
+- [Determining the dimensions of elements](/zh-TW/docs/Determining_the_dimensions_of_elements) (it needs some updating as it was made in the DHTML/Ajax era).
+- [Managing screen orientation](/zh-TW/docs/WebAPI/Managing_screen_orientation)
-Specifications
+## Specifications
{{Specifications}}
-Browser compatibility notes
+## Browser compatibility notes
-All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.
+All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.
diff --git a/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.md b/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.md
index 1015e1bf62fbac..6af9718ae6ca71 100644
--- a/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.md
+++ b/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.md
@@ -3,34 +3,36 @@ title: 控制畫面方向
slug: Web/API/CSS_Object_Model/Managing_screen_orientation
translation_of: Web/API/CSS_Object_Model/Managing_screen_orientation
---
-{{SeeCompatTable}}{{APIRef}}
+{{SeeCompatTable}}{{APIRef}}
-摘要
+## 摘要
-畫面方向(Screen Orientation)與裝置方向(Device Orientation) 略有不同。有時甚至裝置本身不具備方向偵測功能,但裝置的螢幕仍搭載方向功能。如果裝置可測知本身的方向又能控制畫面方向,就能隨時配合 Web Apps 而達到最佳效果。
+畫面方向(Screen Orientation)與[裝置方向(Device Orientation)](/zh-TW/docs/WebAPI/Detecting_device_orientation)略有不同。有時甚至裝置本身不具備方向偵測功能,但裝置的螢幕仍搭載方向功能。如果裝置可測知本身的方向又能控制畫面方向,就能隨時配合 Web Apps 而達到最佳效果。
-現有 2 種方法可處理畫面的方向,但均需搭配 CSS 與 JavaScript。第一種方法就是方向的 Media Query 。根據瀏覽器視窗為橫放(寬度大於高度)或直放(高度大於寬度)狀態,而透過 CSS 調整網頁內容的配置。
+現有 2 種方法可處理畫面的方向,但均需搭配 CSS 與 JavaScript。第一種方法就是方向的 [Media Query](/zh-TW/docs/CSS/Media_queries#orientation)。根據瀏覽器視窗為橫放(寬度大於高度)或直放(高度大於寬度)狀態,而透過 CSS 調整網頁內容的配置。
-第二種方法就是 JavaScript Screen Orientation API,可取得畫面目前的方向並進一步鎖定。
+第二種方法就是 JavaScript Screen Orientation API,可取得畫面目前的方向並進一步鎖定。
-根據方向而調整配置
+## 根據方向而調整配置
-方向改變最常見的情形之一,就是根據裝置的方向而修正內容的配置方式。舉例來說,你可能想將按鈕列拉到與裝置螢幕等長。而透過 Media Query 即可輕鬆達到此效果。
+方向改變最常見的情形之一,就是根據裝置的方向而修正內容的配置方式。舉例來說,你可能想將按鈕列拉到與裝置螢幕等長。而透過 Media Query 即可輕鬆達到此效果。
-來看看下列 HTML 程式碼範例:
+來看看下列 HTML 程式碼範例:
-<ul id="toolbar">
- <li>A</li>
- <li>B</li>
- <li>C</li>
-</ul>
+```html
+
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. Nullam quis malesuada est.</p>
-
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. Nullam quis malesuada est.
+```
-CSS 將根據方向的 Media Query,處理畫面方向的特殊樣式:
+CSS 將根據方向的 Media Query,處理畫面方向的特殊樣式:
-/* First let's define some common styles */
+```css
+/* First let's define some common styles */
html, body {
width : 100%;
@@ -69,11 +71,12 @@ li {
padding: 0.5em;
background: white;
}
-
+```
-在設定某些通用的樣式之後,即可針對方向定義特殊條件:
+在設定某些通用的樣式之後,即可針對方向定義特殊條件:
-/* For portrait, we want the tool bar on top */
+```css
+/* For portrait, we want the tool bar on top */
@media screen and (orientation: portrait) {
#toolbar {
@@ -98,75 +101,59 @@ li {
margin-top: .5em;
}
}
-
+```
-結果如下所示(若無法顯示,可至本文右上角切換回英文原文觀看):
+結果如下所示(若無法顯示,可至本文右上角切換回英文原文觀看):
-
-
-
- Portrait
- Landscape
-
-
-
-
- {{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 180, 350) }}
- {{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 350, 180) }}
-
-
-
+| Portrait | Landscape |
+| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| {{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 180, 350) }} | {{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 350, 180) }} |
-
-
注意: 方向 Media Query 其實是以瀏覽器視窗 (或 iframe) 的方向為準,而非裝置本身的方向。
-
+> **備註:** 方向 Media Query 其實是以瀏覽器視窗 (或 iframe) 的方向為準,而非裝置本身的方向。
-鎖定畫面方向
+## 鎖定畫面方向
-
+> **警告:** 此 API 仍屬實驗性質,目前仍具備 `moz` 前綴而僅能用於 [Firefox OS](/zh-TW/docs/Mozilla/Firefox_OS) 與 [Firefox for Android](/zh-TW/docs/Mozilla/Firefox_for_Android),而 Windows 8.1 以上版本的 Internet Explorer 則使用 `ms` 前綴。
-某些裝置(主要為行動裝置)可根據本身方向而動態改變畫面的方向,讓使用者隨時閱讀畫面上的資訊。這種動作對文字類的內容影響不大,但某些內容就無法順利套用此功能。舉例來說,若遊戲需要裝置方向的相關資訊,就可能因為方向變化而發生混亂情形。
+某些裝置(主要為行動裝置)可根據本身方向而動態改變畫面的方向,讓使用者隨時閱讀畫面上的資訊。這種動作對文字類的內容影響不大,但某些內容就無法順利套用此功能。舉例來說,若遊戲需要裝置方向的相關資訊,就可能因為方向變化而發生混亂情形。
-而 Screen Orientation API 即可用以避免或處理這類變化。
+而 Screen Orientation API 即可用以避免或處理這類變化。
-監聽方向變化
+### 監聽方向變化
-只要裝置改變了畫面方向與本身方向,就會觸發 {{event("orientationchange")}} 事件,再由 {{domxref("Screen.orientation")}} 屬性讀取之。
+只要裝置改變了畫面方向與本身方向,就會觸發 {{event("orientationchange")}} 事件,再由 {{domxref("Screen.orientation")}} 屬性讀取之。
-screen.addEventListener("orientationchange", function () {
+```js
+screen.addEventListener("orientationchange", function () {
console.log("The orientation of the screen is: " + screen.orientation);
});
-
-
-避免方向改變
+```
-任何 Web Apps 均可鎖定畫面以符合本身需求。{{domxref("Screen.lockOrientation()")}} 函式可鎖定畫面方向;{{domxref("Screen.unlockOrientation()")}} 函式可解鎖畫面方向。
+### 避免方向改變
-{{domxref("Screen.lockOrientation()")}} 將接受一組字串或系列字串,以定義畫面鎖定的方向。有效字串為:「portrait-primary
」、「portrait-secondary
」、「landscape-primary
」、「landscape-secondary
」、「portrait
」、「landscape
」。另可參閱 {{domxref("Screen.lockOrientation")}} 進一步了解這些有效值。
+任何 Web Apps 均可鎖定畫面以符合本身需求。{{domxref("Screen.lockOrientation()")}} 函式可鎖定畫面方向;{{domxref("Screen.unlockOrientation()")}} 函式可解鎖畫面方向。
-screen.lockOrientation('landscape');
+{{domxref("Screen.lockOrientation()")}} 將接受一組字串或系列字串,以定義畫面鎖定的方向。有效字串為:「`portrait-primary`」、「`portrait-secondary`」、「`landscape-primary`」、「`landscape-secondary`」、「`portrait`」、「`landscape`」。另可參閱 {{domxref("Screen.lockOrientation")}} 進一步了解這些有效值。
-
-
注意: 畫面鎖定功能將依 Web Apps 而有所不同。如果 App A 鎖定為 landscape
;App B 鎖定為 portrait,則此兩款 Apps 均將維持自己的方向。所以不論如何切換
A 與 B,均不會觸發 {{event("orientationchange")}} 事件。
+```js
+screen.lockOrientation('landscape');
+```
-
但若必須改變方向以滿足畫面鎖定的需求,則鎖定方向時就會觸發 {{event("orientationchange")}} 事件。
-
+> **備註:** 畫面鎖定功能將依 Web Apps 而有所不同。如果 App A 鎖定為 `landscape`;App B 鎖定為 `portrait,則此兩款 Apps 均將維持自己的方向。所以不論如何切換` A 與 B,均不會觸發 {{event("orientationchange")}} 事件。但若必須改變方向以滿足畫面鎖定的需求,則鎖定方向時就會觸發 {{event("orientationchange")}} 事件。
-Firefox OS and Android: Orientation lock using the manifest
+## Firefox OS and Android: Orientation lock using the manifest
-For a Firefox OS and Firefox Android (soon to work on Firefox desktop too) specific way to lock orientation, you can set the orientation field in app's your manifest file, for example:
+For a Firefox OS and Firefox Android (soon to work on Firefox desktop too) specific way to lock orientation, you can set the [orientation](/en-US/Apps/Build/Manifest#orientation) field in app's your manifest file, for example:
-"orientation": "portrait"
+```json
+"orientation": "portrait"
+```
-參見
+## 參見
-
+- {{domxref("Screen.orientation")}}
+- {{domxref("Screen.lockOrientation()")}}
+- {{domxref("Screen.unlockOrientation()")}}
+- {{domxref("Screen.onorientationchange")}}
+- [方向的 Media Query](/zh-TW/docs/CSS/Media_queries#orientation)
+- [Firefox 3.5 的 Media Queries 簡介](http://hacks.mozilla.org/2009/06/media-queries/)
diff --git a/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.md b/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.md
index c8e9540697b432..49b296bf12f4e1 100644
--- a/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.md
+++ b/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.md
@@ -3,53 +3,56 @@ title: 使用動態樣式資訊
slug: Web/API/CSS_Object_Model/Using_dynamic_styling_information
translation_of: Web/API/CSS_Object_Model/Using_dynamic_styling_information
---
-The CSS Object Model (CSSOM), part of the DOM, exposes specific interfaces allowing manipulation of a wide amount of information regarding CSS. Initially defined in the DOM Level 2 Style recommendation, these interfaces forms now a specification, CSS Object Model (CSSOM) which aims at superseding it.
+The CSS Object Model (CSSOM), part of the DOM, exposes specific interfaces allowing manipulation of a wide amount of information regarding CSS. Initially defined in the _DOM Level 2 Style_ recommendation, these interfaces forms now a specification, _CSS Object Model (CSSOM)_ which aims at superseding it.
-In many cases, and where possible, it really is best practice to dynamically manipulate classes via the {{ domxref("element.className", "className") }} property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document.
+In many cases, and where possible, it really is best practice to dynamically manipulate classes via the {{ domxref("element.className", "className") }} property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document.
-The basic style
object exposes the {{domxref("Stylesheet")}} and the {{domxref("CSSStylesheet")}} interfaces. Those interfaces contain members like insertRule
, selectorText
, and parentStyleSheet
for accessing and manipulating the individual style rules that make up a CSS stylesheet.
+The basic `style` object exposes the {{domxref("Stylesheet")}} and the {{domxref("CSSStylesheet")}} interfaces. Those interfaces contain members like `insertRule`, `selectorText`, and `parentStyleSheet` for accessing and manipulating the individual style rules that make up a CSS stylesheet.
-To get to the style
objects from the document
, you can use the {{domxref("document.styleSheets")}} property and access the individual objects by index (e.g., document.styleSheets[0]
is the first stylesheet defined for the document, etc.).
+To get to the `style` objects from the `document`, you can use the {{domxref("document.styleSheets")}} property and access the individual objects by index (e.g., `document.styleSheets[0]` is the first stylesheet defined for the document, etc.).
-透過 CSSOM 修改樣式表規則
+## 透過 CSSOM 修改樣式表規則
-<html>
-<head>
-<title>Modifying a stylesheet rule with CSSOM</title>
-<style type="text/css">
+```html
+
+
+Modifying a stylesheet rule with CSSOM
+
+
+
+
The stylesheet declaration for the body's background color is modified via JavaScript.
-</body>
-</html>
+
+
+```
-{{ EmbedLiveSample('Modify_a_stylesheet_rule') }}
+{{ EmbedLiveSample('Modify_a_stylesheet_rule') }}
-The list of properties available in the DOM from the style property is given on the DOM CSS Properties List page.
+The list of properties available in the DOM from the style property is given on the [DOM CSS Properties List](/zh-TW/docs/DOM/CSS) page.
-To modify styles to a document using CSS syntax, one can insert rules or insert {{HTMLElement("style")}} tags whose innerHTML
property is set to the desired CSS.
+To modify styles to a document using CSS syntax, one can insert rules or insert {{HTMLElement("style")}} tags whose `innerHTML` property is set to the desired CSS.
-修改元素的樣式
+## 修改元素的樣式
-The element {{domxref("HTMLElement.style", "style")}} property (see also the section "DOM Style Object" below) can also be used to get and set the styles on an element. However, this property only returns style attributes that have been set in-line (e.g, <td style="background-color: lightblue">
returns the string "background-color:lightblue
", or directly for that element using element.style.propertyName
, even though there may be other styles on the element from a stylesheet).
+The element {{domxref("HTMLElement.style", "style")}} property (see also the section "DOM Style Object" below) can also be used to get and set the styles on an element. However, this property only returns style attributes that have been set _in-line_ (e.g, ` ` returns the string "`background-color:lightblue`", or directly for that element using `element.style.propertyName`, even though there may be other styles on the element from a stylesheet).
-Also, when you set this property on an element, you override and erase any styles that have been set elsewhere for that element's particular property you are setting. Setting the border property, for example, will override settings made elsewhere for that element's border property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.
+Also, when you set this property on an element, you override and erase any styles that have been set elsewhere for that element's particular property you are setting. Setting the border property, for example, will override settings made elsewhere for that element's border property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.
-To change a particular element's style, you can adapt the following example for the element(s) you want to style.
+To change a particular element's style, you can adapt the following example for the element(s) you want to style.
-<html>
-<head>
-<title>simple style example</title>
+```html
+
+
+simple style example
-<script type="text/javascript">
+
-<style type="text/css">
+
+
-<body>
+
-<!-- passes a reference to the element's object as parameter 'this'. -->
-<p id="p1" onclick="alterStyle(this);">
+
+
Click here to change background color.
-</p>
+
-<!-- passes the 'p1' id of another element's style to modify. -->
-<button onclick="resetStyle('p1');">Reset background color</button>
+
+Reset background color
-</body>
-</html>
-
+
+
+```
-{{ EmbedLiveSample('Modify_an_element_style') }}
+{{ EmbedLiveSample('Modify_an_element_style') }}
-The {{domxref("window.getComputedStyle", "getComputedStyle()")}} method on the document.defaultView
object returns all styles that have actually been computed for an element. See Example 6: getComputedStyle in the examples chapter for more information on how to use this method.
+The {{domxref("window.getComputedStyle", "getComputedStyle()")}} method on the `document.defaultView` object returns all styles that have actually been computed for an element. See [Example 6: getComputedStyle](/en/Gecko_DOM_Reference/Examples#Example_6:_getComputedStyle) in the examples chapter for more information on how to use this method.
-DOM Style Object
+## DOM Style Object
-The style
object represents an individual style statement. Unlike the individual rules available from the document.styleSheets
collection, the style object is accessed from the document
or from the elements to which that style is applied. It represents the in-line styles on a particular element.
+The `style` object represents an individual style statement. Unlike the individual rules available from the [`document.styleSheets`](/en/DOM/document.styleSheets) collection, the style object is accessed from the `document` or from the elements to which that style is applied. It represents the _in-line_ styles on a particular element.
-More important than the two properties noted here is the use of the style
object to set individual style properties on an element:
+More important than the two properties noted here is the use of the `style` object to set individual style properties on an element:
-
-
<!DOCTYPE html>
-<html>
- <head>
- <title>style Property Example</title>
- <link rel="StyleSheet" href="example.css" type="text/css">
- <script type="text/javascript">
+```html hidden
+
+
+
+ style Property Example
+
+
+
- <body>
- <div id="d" class="thunder">Thunder</div>
- <button onclick="stilo()">Click here to change text color</button>
- <button onclick="resetStyle()">Reset text color</button>
- </body>
-</html>
-
-
+
+ Thunder
+ Click here to change text color
+ Reset text color
+
+
+```
-{{ EmbedLiveSample('DOM_Style_Object_code_sample') }}
+{{ EmbedLiveSample('DOM_Style_Object_code_sample') }}
-The media and type of the style may or may not be given.
+The **media** and **type** of the style may or may not be given.
-使用 setAttribute 方法
+### 使用 setAttribute 方法
-Note that you can also change style of an element by getting a reference to it and then use its setAttribute
method to specify the CSS property and its value.
+Note that you can also change style of an element by getting a reference to it and then use its [`setAttribute`](/en/DOM/element.setAttribute) method to specify the CSS property and its value.
-var el = document.getElementById('some-element');
+```js
+var el = document.getElementById('some-element');
el.setAttribute('style', 'background-color:darkblue;');
-
+```
-Be aware, however, that setAttribute
removes all other style properties that may already have been defined in the element's style object. If the some-element
element above had an in–line style attribute of say style="font-size: 18px"
, that value would be removed by the use of setAttribute
.
+Be aware, however, that `setAttribute` removes all other style properties that may already have been defined in the element's style object. If the `some-element` element above had an in–line style attribute of say `style="font-size: 18px"`, that value would be removed by the use of `setAttribute`.
diff --git a/files/zh-tw/web/api/datatransfer/index.md b/files/zh-tw/web/api/datatransfer/index.md
index c8863d061c0f14..d05ca82e892f97 100644
--- a/files/zh-tw/web/api/datatransfer/index.md
+++ b/files/zh-tw/web/api/datatransfer/index.md
@@ -3,97 +3,87 @@ title: DataTransfer
slug: Web/API/DataTransfer
translation_of: Web/API/DataTransfer
---
-{{APIRef("HTML Drag and Drop API")}}
+{{APIRef("HTML Drag and Drop API")}}
-DataTransfer
物件被用來保存使用者於拖放操作過程中的資料,其中可能包含了一至多項資料以及多種資料類型。要瞭解拖放操作的更多細節,請參考拖放操作 一文。
+**`DataTransfer`** 物件被用來保存使用者於拖放操作過程中的資料,其中可能包含了一至多項資料以及多種資料類型。要瞭解拖放操作的更多細節,請參考[拖放操作](/zh-TW/docs/Web/API/HTML_Drag_and_Drop_API)一文。
-DataTransfer
只能是每一種 {{domxref("DragEvent")}} 型別物件的共同屬性-{{domxref("DragEvent.dataTransfer","dataTransfer")}},不能夠被單獨建立。
+`DataTransfer` 只能是每一種 {{domxref("DragEvent")}} 型別物件的共同屬性-{{domxref("DragEvent.dataTransfer","dataTransfer")}},不能夠被單獨建立。
-屬性
+## 屬性
-Standard properties
+### Standard properties
-
- {{domxref("DataTransfer.dropEffect")}}
- Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be none
copy
link
or move
.
- {{domxref("DataTransfer.effectAllowed")}}
- Provides all of the types of operations that are possible. Must be one of none
, copy
, copyLink
, copyMove
, link
, linkMove
, move
, all
or uninitialized
.
- {{domxref("DataTransfer.files")}}
- Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list.
- {{domxref("DataTransfer.items")}} {{readonlyInline}}
- Gives a {{domxref("DataTransferItemList")}} object which is a list of all of the drag data.
- {{domxref("DataTransfer.types")}} {{readonlyInline}}
- An array of {{domxref("DOMString","strings")}} giving the formats that were set in the {{event("dragstart")}} event.
-
+- {{domxref("DataTransfer.dropEffect")}}
+ - : Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be `none` `copy` `link` or `move`.
+- {{domxref("DataTransfer.effectAllowed")}}
+ - : Provides all of the types of operations that are possible. Must be one of `none`, `copy`, `copyLink`, `copyMove`, `link`, `linkMove`, `move`, `all` or `uninitialized`.
+- {{domxref("DataTransfer.files")}}
+ - : Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list.
+- {{domxref("DataTransfer.items")}} {{readonlyInline}}
+ - : Gives a {{domxref("DataTransferItemList")}} object which is a list of all of the drag data.
+- {{domxref("DataTransfer.types")}} {{readonlyInline}}
+ - : An array of {{domxref("DOMString","strings")}} giving the formats that were set in the {{event("dragstart")}} event.
-Gecko properties
+### Gecko properties
-{{SeeCompatTable}}
+{{SeeCompatTable}}
-Note: All of the properties in this section are Gecko-specific.
+> **備註:** All of the properties in this section are Gecko-specific.
-
- {{domxref("DataTransfer.mozCursor")}}
- Gives the drag cursor's state. This is primarily used to control the cursor during tab drags.
- {{domxref("DataTransfer.mozItemCount")}} {{readonlyInline}}
- Gives the number of items in the drag operation.
- {{domxref("DataTransfer.mozSourceNode")}} {{readonlyInline}}
- The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is null
for external drags or if the caller can't access the node.
- {{domxref("DataTransfer.mozUserCancelled")}} {{readonlyInline}}
- This property applies only to the dragend
event, and is true
if the user canceled the drag operation by pressing escape. It will be false
in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location.
-
+- {{domxref("DataTransfer.mozCursor")}}
+ - : Gives the drag cursor's state. This is primarily used to control the cursor during tab drags.
+- {{domxref("DataTransfer.mozItemCount")}} {{readonlyInline}}
+ - : Gives the number of items in the drag operation.
+- {{domxref("DataTransfer.mozSourceNode")}} {{readonlyInline}}
+ - : The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is `null` for external drags or if the caller can't access the node.
+- {{domxref("DataTransfer.mozUserCancelled")}} {{readonlyInline}}
+ - : This property applies only to the `dragend` event, and is `true` if the user canceled the drag operation by pressing escape. It will be `false` in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location.
-方法
+## 方法
-Standard methods
+### Standard methods
-
- {{domxref("DataTransfer.clearData()")}}
- Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.
- {{domxref("DataTransfer.getData()")}}
- Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.
- {{domxref("DataTransfer.setData()")}}
- Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position.
- {{domxref("DataTransfer.setDragImage()")}}
- Set the image to be used for dragging if a custom one is desired.
-
+- {{domxref("DataTransfer.clearData()")}}
+ - : Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.
+- {{domxref("DataTransfer.getData()")}}
+ - : Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.
+- {{domxref("DataTransfer.setData()")}}
+ - : Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position.
+- {{domxref("DataTransfer.setDragImage()")}}
+ - : Set the image to be used for dragging if a custom one is desired.
-Gecko methods
+### Gecko methods
-{{SeeCompatTable}}
+{{SeeCompatTable}}
-Note: All of the methods in this section are Gecko-specific.
+> **備註:** All of the methods in this section are Gecko-specific.
-
- {{domxref("DataTransfer.addElement()")}}
- Sets the drag source to the given element.
- {{domxref("DataTransfer.mozClearDataAt()")}}
- Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.
- {{domxref("DataTransfer.mozGetDataAt()")}}
- Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.
- {{domxref("DataTransfer.mozSetDataAt()")}}
- A data transfer may store multiple items, each at a given zero-based index. mozSetDataAt()
may only be called with an index argument less than mozItemCount
in which case an existing item is modified, or equal to mozItemCount
in which case a new item is added, and the mozItemCount
is incremented by one.
- {{domxref("DataTransfer.mozTypesAt()")}}
- Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.
-
+- {{domxref("DataTransfer.addElement()")}}
+ - : Sets the drag source to the given element.
+- {{domxref("DataTransfer.mozClearDataAt()")}}
+ - : Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.
+- {{domxref("DataTransfer.mozGetDataAt()")}}
+ - : Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.
+- {{domxref("DataTransfer.mozSetDataAt()")}}
+ - : A data transfer may store multiple items, each at a given zero-based index. `mozSetDataAt()` may only be called with an index argument less than `mozItemCount` in which case an existing item is modified, or equal to `mozItemCount` in which case a new item is added, and the `mozItemCount` is incremented by one.
+- {{domxref("DataTransfer.mozTypesAt()")}}
+ - : Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.
-範例
+## 範例
-Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.
+Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.DataTransfer")}}
-參見
+## 參見
-
+- [Drag and drop](/Web/Guide/HTML/Drag_and_drop)
+- [Drag Operations](/Web/Guide/HTML/Drag_operations)
+- [Recommended Drag Types](/Web/Guide/HTML/Recommended_Drag_Types)
+- [Dragging and Dropping Multiple Items](/Web/Guide/HTML/Dragging_and_Dropping_Multiple_Items)
diff --git a/files/zh-tw/web/api/devicemotionevent/index.md b/files/zh-tw/web/api/devicemotionevent/index.md
index 42452dbab79c09..23ee6d23ce60d0 100644
--- a/files/zh-tw/web/api/devicemotionevent/index.md
+++ b/files/zh-tw/web/api/devicemotionevent/index.md
@@ -3,49 +3,45 @@ title: DeviceMotionEvent
slug: Web/API/DeviceMotionEvent
translation_of: Web/API/DeviceMotionEvent
---
-{{apiref("Device Orientation Events")}}{{SeeCompatTable}}
+{{apiref("Device Orientation Events")}}{{SeeCompatTable}}
-概要
+## 概要
-DeviceMotionEvent
提供了網頁開發者關於裝置位置及旋轉方向改變時的速度資訊。
+`DeviceMotionEvent` 提供了網頁開發者關於裝置位置及旋轉方向改變時的速度資訊。
-
-
Warning: Currently, Firefox and Chrome does not handle the coordinates the same way. Take care about this while using them.
-
+> **警告:** Currently, Firefox and Chrome does not handle the coordinates the same way. Take care about this while using them.
-屬性
+## 屬性
-
- {{domxref("DeviceMotionEvent.acceleration")}} {{readonlyinline}}
- An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in m/s2 .
- {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}} {{readonlyinline}}
- An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in m/s2 .
- {{domxref("DeviceMotionEvent.rotationRate")}} {{readonlyinline}}
- An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds.
- {{domxref("DeviceMotionEvent.interval")}} {{readonlyinline}}
- A number representing the interval of time, in milliseconds, at which data is obtained from the device.
-
+- {{domxref("DeviceMotionEvent.acceleration")}} {{readonlyinline}}
+ - : An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in [m/s2](https://en.wikipedia.org/wiki/Meter_per_second_squared).
+- {{domxref("DeviceMotionEvent.accelerationIncludingGravity")}} {{readonlyinline}}
+ - : An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in [m/s2](https://en.wikipedia.org/wiki/Meter_per_second_squared).
+- {{domxref("DeviceMotionEvent.rotationRate")}} {{readonlyinline}}
+ - : An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds.
+- {{domxref("DeviceMotionEvent.interval")}} {{readonlyinline}}
+ - : A number representing the interval of time, in milliseconds, at which data is obtained from the device.
-範例
+## 範例
-window.addEventListener('devicemotion', function(event) {
+```js
+window.addEventListener('devicemotion', function(event) {
console.log(event.acceleration.x + ' m/s2');
-});
+});
+```
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.DeviceMotionEvent")}}
-參見
+## 參見
-
+- {{ event("deviceorientation") }}
+- {{ domxref("DeviceMotionEvent") }}
+- {{ event("devicemotion") }}
+- [Detecting device orientation](/zh-TW/docs/WebAPI/Detecting_device_orientation)
+- [Orientation and motion data explained](/en/DOM/Orientation_and_motion_data_explained)
diff --git a/files/zh-tw/web/api/document/createelement/index.md b/files/zh-tw/web/api/document/createelement/index.md
index fe011024c99a0a..266ff0b038c2ba 100644
--- a/files/zh-tw/web/api/document/createelement/index.md
+++ b/files/zh-tw/web/api/document/createelement/index.md
@@ -3,50 +3,51 @@ title: Document.createElement()
slug: Web/API/Document/createElement
translation_of: Web/API/Document/createElement
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-於 HTML 文件中,Document.createElement()
方法可以依指定的標籤名稱(tagName
)建立 HTML 元素,或是在未定義標籤名稱下建立一個 {{domxref("HTMLUnknownElement")}}。在 XUL 文件中,Document.createElement()
將會建立指定的 XUL 元素。而在其它文件,則會建立一個 namespace URI 為 null
的元素。
+於 [HTML](/zh-TW/docs/Web/HTML) 文件中,**`Document.createElement()`** 方法可以依指定的標籤名稱(`tagName`)建立 HTML 元素,或是在未定義標籤名稱下建立一個 {{domxref("HTMLUnknownElement")}}。在 [XUL](/zh-TW/docs/Mozilla/Tech/XUL) 文件中,`Document.createElement()` 將會建立指定的 XUL 元素。而在其它文件,則會建立一個 namespace URI 為 `null` 的元素。
-若要明確指定元素的 namespace URI,請使用 document.createElementNS()
。
+若要明確指定元素的 namespace URI,請使用 [`document.createElementNS()`](/zh-TW/docs/Web/API/Document/createElementNS)。
-語法
+## 語法
-var element = document .createElement(tagName[, options] );
-
+```js
+var element = document.createElement(tagName[, options]);
+```
-參數
+### 參數
-
- tagName
- 一個指定類型給所創建的元素的字串。{{domxref("Node.nodeName", "nodeName")}} 創建的元素由 tagName
的值初始,不要使用吻合名稱(例如 "html:a")。當該方法在 HTML 文件中被調用時,createElement()
會先將 tagName
轉化為小寫後再創建元素。在 Firefox、Opera 和 Chrome,createElement(null)
與 createElement("null")
作用相同。
- options
{{optional_inline}}
- 選擇性 ElementCreationOptions
物件包含一個屬性 is
,它的值是先前使用customElements.define()
所定義的自定義元素的標籤名稱。為了與以前的 自定義元素規範 相容,一些瀏覽器將允許你在此傳遞一個字串而非物件,其字串的值就是自定義元件的標籤名稱。了解更多訊息以及如何使用此參數,可以參閱 擴展原生 HTML 元素 。新元素將被賦予一個 is
屬性,其值就是自定義元素的標籤名稱。自定義元素算是實驗中的功能,因此目前只作用於部分瀏覽器中。
-
+- `tagName`
+ - : 一個指定類型給所創建的元素的字串。{{domxref("Node.nodeName", "nodeName")}} 創建的元素由 `tagName` 的值初始,不要使用吻合名稱(例如 "html:a")。當該方法在 HTML 文件中被調用時,`createElement()` 會先將 `tagName` 轉化為小寫後再創建元素。在 Firefox、Opera 和 Chrome,`createElement(null)` 與 `createElement("null")` 作用相同。
+- `options`{{optional_inline}}
+ - : 選擇性 `ElementCreationOptions` 物件包含一個屬性 `is`,它的值是先前使用`customElements.define()` 所定義的自定義元素的標籤名稱。為了與以前的 [自定義元素規範](https://www.w3.org/TR/custom-elements/) 相容,一些瀏覽器將允許你在此傳遞一個字串而非物件,其字串的值就是自定義元件的標籤名稱。了解更多訊息以及如何使用此參數,可以參閱 [擴展原生 HTML 元素](https://developers.google.com/web/fundamentals/primers/customelements/#extendhtml)。新元素將被賦予一個 `is` 屬性,其值就是自定義元素的標籤名稱。自定義元素算是實驗中的功能,因此目前只作用於部分瀏覽器中。
-回傳值
+### 回傳值
-一個新的 Element
.
+一個新的 [`Element`](/zh-TW/docs/Web/API/Element).
-範例
+## 範例
-這邊創建一個新的 <div>
,並將它插入到 ID div1
之前。
+這邊創建一個新的 `` ,並將它插入到 ID `div1` 之前。
-
HTML
+### HTML
-
<!DOCTYPE html>
-<html>
-<head>
- <title>||Working with elements||</title>
-</head>
-<body>
- <div id="div1">The text above has been created dynamically.</div>
-</body>
-</html>
-
+```html
+
+
+
+
||Working with elements||
+
+
+
The text above has been created dynamically.
+
+
+```
-
JavaScript
+### JavaScript
-
document.body.onload = addElement;
+```js
+document.body.onload = addElement;
function addElement () {
// create a new div element
@@ -58,24 +59,23 @@ function addElement () {
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
-}
+}
+```
-
{{EmbedLiveSample("Example", 500, 50)}}
+{{EmbedLiveSample("範例", 500, 50)}}
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Document.createElement")}}
-
參見
+## 參見
-
- {{domxref("Node.removeChild()")}}
- {{domxref("Node.replaceChild()")}}
- {{domxref("Node.appendChild()")}}
- {{domxref("Node.insertBefore()")}}
- {{domxref("Node.hasChildNodes()")}}
-
+- {{domxref("Node.removeChild()")}}
+- {{domxref("Node.replaceChild()")}}
+- {{domxref("Node.appendChild()")}}
+- {{domxref("Node.insertBefore()")}}
+- {{domxref("Node.hasChildNodes()")}}
diff --git a/files/zh-tw/web/api/document/createtreewalker/index.md b/files/zh-tw/web/api/document/createtreewalker/index.md
index 67008389735ee8..e04eecd5a5ad9f 100644
--- a/files/zh-tw/web/api/document/createtreewalker/index.md
+++ b/files/zh-tw/web/api/document/createtreewalker/index.md
@@ -4,109 +4,48 @@ slug: Web/API/Document/createTreeWalker
translation_of: Web/API/Document/createTreeWalker
original_slug: 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.
-
-
-
-
-
-
-
-
- NodeFilter.SHOW_ALL
- -1
(that is the max value of unsigned long
)
- 顯示所有節點.
-
-
- NodeFilter.
SHOW_ATTRIBUTE
{{deprecated_inline}}
- 2
- Shows 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}}
- 8
- Shows {{ domxref("CDATASection") }} nodes.
-
-
- NodeFilter.
SHOW_COMMENT
- 128
- Shows {{ domxref("Comment") }} nodes.
-
-
- NodeFilter.
SHOW_DOCUMENT
- 256
- Shows {{ domxref("Document") }} nodes.
-
-
- NodeFilter.
SHOW_DOCUMENT_FRAGMENT
- 1024
- Shows {{ domxref("DocumentFragment") }} nodes.
-
-
- NodeFilter.
SHOW_DOCUMENT_TYPE
- 512
- Shows {{ domxref("DocumentType") }} nodes.
-
-
- NodeFilter.
SHOW_ELEMENT
- 1
- Shows {{ domxref("Element") }} nodes.
-
-
- NodeFilter.
SHOW_ENTITY
{{deprecated_inline}}
- 32
- Shows {{ 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}}
- 16
- Shows {{ domxref("EntityReference") }} nodes.
-
-
- NodeFilter.
SHOW_NOTATION
{{deprecated_inline}}
- 2048
- Shows {{ 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_INSTRUCTION
- 64
- Shows {{ domxref("ProcessingInstruction") }} nodes.
-
-
- NodeFilter.
SHOW_TEXT
- 4
- 顯示文字節點({{ domxref("Text") }} nodes).
-
-
-
-
-
- filter {{optional_inline}}
-
- 是一個可選的 {{domxref("NodeFilter")}}, 這是一個物件有著 acceptNode
方法, 這方法被 {{domxref("TreeWalker")}} 呼叫來決定是否接受通過 whatToShow
檢查的節點.
-
- entityReferenceExpansion {{optional_inline}} {{Deprecated_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(
+{{ApiRef("Document")}}
+
+**`Document.createTreeWalker()`** 方法,能建立一個 {{domxref("TreeWalker")}} 物件並傳回.
+
+## 語法
+
+```plain
+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`](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-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}} | `2` | Shows 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}} | `8` | Shows {{ domxref("CDATASection") }} nodes. |
+ | `NodeFilter.SHOW_COMMENT` | `128` | Shows {{ domxref("Comment") }} nodes. |
+ | `NodeFilter.SHOW_DOCUMENT` | `256` | Shows {{ domxref("Document") }} nodes. |
+ | `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows {{ domxref("DocumentFragment") }} nodes. |
+ | `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows {{ domxref("DocumentType") }} nodes. |
+ | `NodeFilter.SHOW_ELEMENT` | `1` | Shows {{ domxref("Element") }} nodes. |
+ | `NodeFilter.SHOW_ENTITY` {{deprecated_inline}} | `32` | Shows {{ 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}} | `16` | Shows {{ domxref("EntityReference") }} nodes. |
+ | `NodeFilter.SHOW_NOTATION` {{deprecated_inline}} | `2048` | Shows {{ 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_INSTRUCTION` | `64` | Shows {{ domxref("ProcessingInstruction") }} nodes. |
+ | `NodeFilter.SHOW_TEXT` | `4` | 顯示文字節點({{ domxref("Text") }} nodes). |
+- _filter_ {{optional_inline}}
+ - : 是一個可選的 {{domxref("NodeFilter")}}, 這是一個物件有著 `acceptNode` 方法, 這方法被 {{domxref("TreeWalker")}} 呼叫來決定是否接受通過 `whatToShow` 檢查的節點.
+- _entityReferenceExpansion_ {{optional_inline}} {{Deprecated_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.
+
+```js
+var treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
@@ -116,14 +55,17 @@ original_slug: Web/API/document.createTreeWalker
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
-
-
Specifications
+```
+
+## Specifications
+
{{Specifications}}
-
Browser compatibility
+
+## Browser compatibility
+
{{Compat("api.Document.createTreeWalker")}}
-
See also
-
+## See also
+
+- The interface of the object it creates: {{domxref("TreeWalker")}}.
+- [createTreeWalker on MSDN](
)
diff --git a/files/zh-tw/web/api/document/execcommand/index.md b/files/zh-tw/web/api/document/execcommand/index.md
index 4faca1b9b51b36..b3e43474b0b989 100644
--- a/files/zh-tw/web/api/document/execcommand/index.md
+++ b/files/zh-tw/web/api/document/execcommand/index.md
@@ -3,169 +3,164 @@ title: Document.execCommand()
slug: Web/API/Document/execCommand
translation_of: Web/API/Document/execCommand
---
-{{ApiRef("DOM")}}{{deprecated_header}}
-
-當 HTML 文件(document)被切換到 designMode
時,它的 document
物件就會對外暴露 execCommand
方法作為操控目前可編輯區域的指令,譬如 form inputs 或 contentEditable
元素。
-
-多數的指令會作用在文件的選取 (粗體、斜體等),而其他則像是插入新的元素(新增一個連結)或是影響一整列的文字(縮排)。當使用 contentEditable
時, execCommand()
會作用在目前活躍的可編輯元素上。
-
-語法
-
-document .execCommand(aCommandName , aShowDefaultUI , aValueArgument )
-
-
-回傳值
-
-如果該指令不被支援或停用將回傳一個 false
的 {{jsxref('Boolean')}} 值。
-
-
-
備註 :只有在使用者互動的部分回傳 true
。請不要嘗試在呼叫指令前使用回傳值來確認瀏覽器是否支援。
-
-
-參數
-
-
- aCommandName
- 一個 {{domxref("DOMString")}} 作為指定要執行的指令。所有可用的指令列表請見 指令 。
- aShowDefaultUI
- 一個 {{jsxref("Boolean")}} 作為指示是否顯示預設的使用者介面。 Mozilla 並未實作這項功能。
- aValueArgument
- 針對需要提供輸入引數的指令,藉由 {{domxref("DOMString")}} 提供相關的資訊。譬如, insertImage
需要提供圖片的 URL 。若沒有引數的需求則可指定為 null
。
-
-
-指令
-
-
- backColor
- 變更文件的背景色彩。在 styleWithCss
模式中,它作用於涵蓋區域的背景色彩。這個指令需要提供一個 {{cssxref("<color>")}} 值字串作為引數值。請留意, Internet Explorer 使用這個指令作為設定文字的背景色彩。
- bold
- 切換選取區域插入點的粗體與否。 Internet Explorer 使用 {{HTMLElement("strong")}} 標籤而不是 {{HTMLElement("b")}}.
- ClearAuthenticationCache
- 清除所有快取中的驗證憑證。
- contentReadOnly
- 使內容文件成為唯讀或可編輯。此指令需要提供布林值 true/false 作為引數值。(Internet Explorer 不支援)。
- copy
- 複製目前選取的區域到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。如果你有使用這個指令的情境,請先查閱相容性表格來決定如何使用。
- createLink
- 對選取的區域建立超連結,僅限於有選取內容。需要提供一個 URI 字串值作為超連結的 href
。 URI 必須最少包含一個字元且可以是空白字元(Internet Explorer 會建立一個 null
值的連結)。
- cut
- 移除目前選取的區域並複製到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。使用細節請查閱相容性表格 。
- decreaseFontSize
- 在選取區域或插入點的前後加入一個 {{HTMLElement("small")}} 標籤( Internet Explorer 不支援)
- defaultParagraphSeparator
- 變更可編輯文字區域於新增段落時的段落分隔器。更多細節請查閱 產生 markup 的區別 。
- delete
- 刪除目前選取的區域。
- enableAbsolutePositionEditor
- 啟用或停用用於移動絕對定位元素的抓取器。這個指令在 Firefox 63 Beta/Dev 版本中預設停用({{bug(1449564)}})。
- enableInlineTableEditing
- 啟用或停用表格的列 / 欄的插入及刪除。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
- enableObjectResizing
- 啟用或停用圖片、表格、絕對定位元素、其他可重設大小物件的重設大小處理。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
- fontName
- 變更選取區域或插入點的字型名稱。此指令需要字型名稱字串(如「Arial」)作為引數值。
- fontSize
- 變更選取區域或插入點的字型大小。此指令需要 1
-7
的整數作為引數值。
- foreColor
- 變更選取區域或插入點的字型色彩。此指令需要十六進位的色彩字串作為引數值。
- formatBlock
- 在目前選取區域的前後加入一個 HTML 區塊層級元素,若選取區域已經存在區塊元素則取代之。(在 Firefox 中, {{HTMLElement("blockquote")}} 是個例外——它會包裹住任何所包含的區塊元素)。 此指令需要一個標籤名稱字串作為引數值。幾乎所有區塊層級元素都可以使用(Internet Explorer and Edge 僅支援標題標籤 H1
–H6
、 ADDRESS
、 PRE
且必須由角括號包裹起來,譬如 "<H1>"
)。
- forwardDelete
- 刪除游標位置後的字元,等同於在 Windows 按下 Delete 鍵盤按鍵。
- heading
- 在選取區域或插入點前後加入一個標題元素。此指令需要標籤名稱字串作為引數值(例:"H1"
, "H6"
)(Internet Explorer 及 Safari 不支援)。
- hiliteColor
- 變更選取區域或插入點的背景色彩。此指令需要一個色彩字串作為引數值。 useCSS
必須為 true
才能有作用(Internet Explorer 不支援)。
- increaseFontSize
- 在選取區域或插入點前後加入一個 {{HTMLElement("big")}} 標題(Internet Explorer 不支援)。
- indent
- 縮排選取區域或插入點所包含的列。在 Firefox ,如果選取的範圍跨越多列且不同的縮排層級,只有選取中最淺層縮排列的才會被縮排。
- insertBrOnReturn
- 控制 Enter 按鍵按下時在目前區塊元素中插入 {{HTMLElement("br")}} 元素或分割成為兩個元素(Internet Explorer 不支援)。
- insertHorizontalRule
- 在插入點插入一個 {{HTMLElement("hr")}} 元素或以它取代選取的內容。
- insertHTML
- 在插入點插入一個 HTML 字串(會刪除選取內容)需要一個有效的 HTML 字串作為引數值(Internet Explorer 不支援)。
- insertImage
- 在插入點插入一個圖片(會刪除選取內容)。需要一個 URL 字串作為圖片的 src
引數值。這個需求跟 createLink
的字串是一樣的。
- insertOrderedList
- 在選取區域或插入點建立一個有序的清單 。
- insertUnorderedList
- 在選取區域或插入點建立一個無序的清單 。
- insertParagraph
- 在選取區域或目前列的前後插入段落 (Internet Explorer 會在插入點插入段落並刪除選取的內容)。
- insertText
- 在插入點處插入給予的純文字(選取內容將被刪除)。
- italic
- 切換選取區域或插入點的斜體開關(Internet Explorer 使用 {{HTMLElement("em")}} 元素而不是 {{HTMLElement("i")}} )。
- justifyCenter
- 置中對齊選取區域或插入點的內容。
- justifyFull
- 左右對齊選取區域或插入點的內容。
- justifyLeft
- 靠左對齊選取區域或插入點的內容。
- justifyRight
- 靠右對齊選取區域或插入點的內容。
- outdent
- 凸排選取區域或插入點所包含的列。
- paste
- 在目前的插入點貼上剪貼簿的內容(取代目前選取的項目)。網頁內容無法使用。詳閱 [1]。
- redo
- 復原上一個取消的指令。
- removeFormat
- 移除目前選取區域所有的格式。
- selectAll
- 選取可編輯區域的所有內容。
- strikeThrough
- 切換選取區域或插入點的刪除線開關。
- subscript
- 切換選取區域或插入點的 subscript 開關。
- superscript
- 切換選取區域或插入點的 superscript 開關。
- underline
- 切換選取區域或插入點的底線 開關。
- undo
- 取消上一個執行的指令。
- unlink
- 從選取的超連結刪除錨點元素 。
- useCSS
{{Deprecated_inline}}
- 針對產生的 markup 使用 HTML 標籤或 CSS。此指令需要一個布林值 true/false 作為引數值。注意:這個引述在邏輯上是反向的(舉例:使用 false
會使用 CSS ,反之使用 true
則使用 HTML 且 Internet Explorer 不支援。這個指令已經被棄用並由 styleWithCSS
取而代之。
- styleWithCSS
- 取代 useCSS
的指令。 true
會在 markup 修改 / 產生 style
屬性, false 會產生展示用的元素。
-
-
-範例
-
-一個在 CodePen 上展示如果使用 的範例。
-
-規格
+{{ApiRef("DOM")}}{{deprecated_header}}
+
+當 HTML 文件(document)被切換到 [`designMode`](/en-US/docs/Web/API/Document/designMode) 時,它的 `document` 物件就會對外暴露 **`execCommand`** 方法作為操控目前可編輯區域的指令,譬如 [form inputs](/zh-TW/docs/Web/HTML/Element/input) 或 [`contentEditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) 元素。
+
+多數的指令會作用在文件的[選取](/zh-TW/docs/Web/API/Selection) (粗體、斜體等),而其他則像是插入新的元素(新增一個連結)或是影響一整列的文字(縮排)。當使用 `contentEditable` 時, `execCommand()` 會作用在目前活躍的可編輯元素上。
+
+## 語法
+
+```plain
+document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+```
+
+### 回傳值
+
+如果該指令不被支援或停用將回傳一個 `false` 的 {{jsxref('Boolean')}} 值。
+
+> **備註:** 只有在使用者互動的部分回傳 `true` 。請不要嘗試在呼叫指令前使用回傳值來確認瀏覽器是否支援。
+
+### 參數
+
+- `aCommandName`
+ - : 一個 {{domxref("DOMString")}} 作為指定要執行的指令。所有可用的指令列表請見 [指令](#指令) 。
+- `aShowDefaultUI`
+ - : 一個 {{jsxref("Boolean")}} 作為指示是否顯示預設的使用者介面。 Mozilla 並未實作這項功能。
+- `aValueArgument`
+ - : 針對需要提供輸入引數的指令,藉由 {{domxref("DOMString")}} 提供相關的資訊。譬如, `insertImage` 需要提供圖片的 URL 。若沒有引數的需求則可指定為 `null` 。
+
+### 指令
+
+- `backColor`
+ - : 變更文件的背景色彩。在 `styleWithCss` 模式中,它作用於涵蓋區域的背景色彩。這個指令需要提供一個 {{cssxref("<color>")}} 值字串作為引數值。請留意, Internet Explorer 使用這個指令作為設定文字的背景色彩。
+- `bold`
+ - : 切換選取區域插入點的粗體與否。 Internet Explorer 使用 {{HTMLElement("strong")}} 標籤而不是 {{HTMLElement("b")}}.
+- `ClearAuthenticationCache`
+ - : 清除所有快取中的驗證憑證。
+- `contentReadOnly`
+ - : 使內容文件成為唯讀或可編輯。此指令需要提供布林值 true/false 作為引數值。(Internet Explorer 不支援)。
+- `copy`
+ - : 複製目前選取的區域到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。如果你有使用這個指令的情境,請先查閱相容性表格來決定如何使用。
+- `createLink`
+ - : 對選取的區域建立超連結,僅限於有選取內容。需要提供一個 [URI](/zh-TW/docs/Archive/Mozilla/URIs_and_URLs) 字串值作為超連結的 `href` 。 URI 必須最少包含一個字元且可以是空白字元(Internet Explorer 會建立一個 `null` 值的連結)。
+- `cut`
+ - : 移除目前選取的區域並複製到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。使用細節請查閱[相容性表格](#Browser_compatibility)。
+- `decreaseFontSize`
+ - : 在選取區域或插入點的前後加入一個 {{HTMLElement("small")}} 標籤( Internet Explorer 不支援)
+- `defaultParagraphSeparator`
+ - : 變更可編輯文字區域於新增段落時的段落分隔器。更多細節請查閱 [產生 markup 的區別](/zh-TW/docs/Web/Guide/HTML/Editable_content#Differences_in_markup_generation)。
+- `delete`
+ - : 刪除目前選取的區域。
+- `enableAbsolutePositionEditor`
+ - : 啟用或停用用於移動絕對定位元素的抓取器。這個指令在 Firefox 63 Beta/Dev 版本中預設停用({{bug(1449564)}})。
+- `enableInlineTableEditing`
+ - : 啟用或停用表格的列 / 欄的插入及刪除。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
+- `enableObjectResizing`
+ - : 啟用或停用圖片、表格、絕對定位元素、其他可重設大小物件的重設大小處理。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
+- `fontName`
+ - : 變更選取區域或插入點的字型名稱。此指令需要字型名稱字串(如「Arial」)作為引數值。
+- `fontSize`
+ - : 變更選取區域或插入點的字型大小。此指令需要 `1`-`7` 的整數作為引數值。
+- `foreColor`
+ - : 變更選取區域或插入點的字型色彩。此指令需要十六進位的色彩字串作為引數值。
+- `formatBlock`
+ - : 在目前選取區域的前後加入一個 HTML 區塊層級元素,若選取區域已經存在區塊元素則取代之。(在 Firefox 中, {{HTMLElement("blockquote")}} 是個例外——它會包裹住任何所包含的區塊元素)。 此指令需要一個標籤名稱字串作為引數值。幾乎所有區塊層級元素都可以使用(Internet Explorer and Edge 僅支援標題標籤 `H1`–`H6` 、 `ADDRESS` 、 `PRE` 且必須由角括號包裹起來,譬如 `""` )。
+- `forwardDelete`
+ - : 刪除游標位置後的字元,等同於在 Windows 按下 Delete 鍵盤按鍵。
+- `heading`
+ - : 在選取區域或插入點前後加入一個標題元素。此指令需要標籤名稱字串作為引數值(例:`"H1"`, `"H6"` )(Internet Explorer 及 Safari 不支援)。
+- `hiliteColor`
+ - : 變更選取區域或插入點的背景色彩。此指令需要一個色彩字串作為引數值。 `useCSS` 必須為 `true` 才能有作用(Internet Explorer 不支援)。
+- `increaseFontSize`
+ - : 在選取區域或插入點前後加入一個 {{HTMLElement("big")}} 標題(Internet Explorer 不支援)。
+- `indent`
+ - : 縮排選取區域或插入點所包含的列。在 Firefox ,如果選取的範圍跨越多列且不同的縮排層級,只有選取中最淺層縮排列的才會被縮排。
+- `insertBrOnReturn`
+ - : 控制 Enter 按鍵按下時在目前區塊元素中插入 {{HTMLElement("br")}} 元素或分割成為兩個元素(Internet Explorer 不支援)。
+- `insertHorizontalRule`
+ - : 在插入點插入一個 {{HTMLElement("hr")}} 元素或以它取代選取的內容。
+- `insertHTML`
+ - : 在插入點插入一個 HTML 字串(會刪除選取內容)需要一個有效的 HTML 字串作為引數值(Internet Explorer 不支援)。
+- `insertImage`
+ - : 在插入點插入一個圖片(會刪除選取內容)。需要一個 URL 字串作為圖片的 `src` 引數值。這個需求跟 `createLink` 的字串是一樣的。
+- `insertOrderedList`
+ - : 在選取區域或插入點建立一個[有序的清單](/zh-TW/docs/Web/HTML/Element/ol)。
+- `insertUnorderedList`
+ - : 在選取區域或插入點建立一個[無序的清單](/zh-TW/docs/Web/HTML/Element/ul)。
+- `insertParagraph`
+ - : 在選取區域或目前列的前後插入[段落](/zh-TW/docs/Web/HTML/Element/p)(Internet Explorer 會在插入點插入段落並刪除選取的內容)。
+- `insertText`
+ - : 在插入點處插入給予的純文字(選取內容將被刪除)。
+- `italic`
+ - : 切換選取區域或插入點的斜體開關(Internet Explorer 使用 {{HTMLElement("em")}} 元素而不是 {{HTMLElement("i")}} )。
+- `justifyCenter`
+ - : 置中對齊選取區域或插入點的內容。
+- `justifyFull`
+ - : 左右對齊選取區域或插入點的內容。
+- `justifyLeft`
+ - : 靠左對齊選取區域或插入點的內容。
+- `justifyRight`
+ - : 靠右對齊選取區域或插入點的內容。
+- `outdent`
+ - : 凸排選取區域或插入點所包含的列。
+- `paste`
+ - : 在目前的插入點貼上剪貼簿的內容(取代目前選取的項目)。網頁內容無法使用。詳閱 \[1]。
+- `redo`
+ - : 復原上一個取消的指令。
+- `removeFormat`
+ - : 移除目前選取區域所有的格式。
+- `selectAll`
+ - : 選取可編輯區域的所有內容。
+- `strikeThrough`
+ - : 切換選取區域或插入點的刪除線開關。
+- `subscript`
+ - : 切換選取區域或插入點的 [subscript](/zh-TW/docs/Web/HTML/Element/sub) 開關。
+- `superscript`
+ - : 切換選取區域或插入點的 [superscript](/zh-TW/docs/Web/HTML/Element/sup) 開關。
+- `underline`
+ - : 切換選取區域或插入點的[底線](/zh-TW/docs/Web/HTML/Element/u)開關。
+- `undo`
+ - : 取消上一個執行的指令。
+- `unlink`
+ - : 從選取的超連結刪除[錨點元素](/zh-TW/docs/Web/HTML/Element/a)。
+- `useCSS` {{Deprecated_inline}}
+ - : 針對產生的 markup 使用 HTML 標籤或 CSS。此指令需要一個布林值 true/false 作為引數值。注意:這個引述在邏輯上是反向的(舉例:使用 `false` 會使用 CSS ,反之使用 `true` 則使用 HTML 且 Internet Explorer 不支援。這個指令已經被棄用並由 `styleWithCSS` 取而代之。
+- `styleWithCSS`
+ - : 取代 `useCSS` 的指令。 `true` 會在 markup 修改 / 產生 `style` 屬性, false 會產生展示用的元素。
+
+## 範例
+
+一個在 CodePen 上展示[如果使用](https://codepen.io/chrisdavidmills/full/gzYjag/)的範例。
+
+## 規格
-瀏覽器相容性
+## 瀏覽器相容性
+{{Compat("api.Document.execCommand")}}
+## 相關資訊
-{{Compat("api.Document.execCommand")}}
-
-相關資訊
-
-
+- {{domxref("HTMLElement.contentEditable")}}
+- {{domxref("document.designMode")}}
+- [Rich-Text Editing in Mozilla](/zh-TW/docs/Rich-Text_Editing_in_Mozilla)
+- [Scribe's "Browser Inconsistencies" documentation](https://github.com/guardian/scribe/blob/master/BROWSERINCONSISTENCIES.md) with bugs related to `document.execCommand`.
diff --git a/files/zh-tw/web/api/document/index.md b/files/zh-tw/web/api/document/index.md
index c71397a30c4023..7675935173eebf 100644
--- a/files/zh-tw/web/api/document/index.md
+++ b/files/zh-tw/web/api/document/index.md
@@ -11,364 +11,340 @@ tags:
- TopicStub
translation_of: Web/API/Document
---
-{{APIRef}}
-
-
-
-Document
介面代表所有在瀏覽器中載入的網頁,也是作為網頁內容 DOM 樹 (包含如 {{HTMLElement("body")}}、{{HTMLElement("table")}} 與其它的{{domxref("Element", "元素")}})的進入點。Document
提供了網頁文件所需的通用函式,例如取得頁面 URL 或是建立網頁文件中新的元素節點等。
-
-{{inheritanceDiagram}}
-
-Document
介面描述了各種類型文件的共同屬性與方法。根據文件的類型(如 HTML 、XML 、SVG 等),也會擁有各自的 API:HTML 文件(content type 為 text/html
)實作了 {{domxref("HTMLDocument")}} 介面,而 XML 及 SVG 文件實作了 {{domxref("XMLDocument")}} 介面。
-
-請注意 window.document
物件為 HTMLDocument
所建構。
-
-屬性
-
-這個介面繼承了 {{domxref("Node")}} 以及 {{domxref("EventTarget")}} 介面。
-
-
- {{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
- Provides access to all elements with an id
. This is a legacy, non-standard interface and you should use the {{domxref("document.getElementById()")}} method instead.
- {{domxref("Document.async")}} {{Deprecated_inline}}
- Used with {{domxref("Document.load")}} to indicate an asynchronous request.
- {{domxref("Document.characterSet")}} {{readonlyinline}}
- Returns the character set being used by the document.
- {{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
- Alias of {{domxref("Document.characterSet")}}. Use this property instead.
- {{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
- Indicates whether the document is rendered in quirks or strict mode.
- {{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
- Returns the Content-Type from the MIME Header of the current document.
- {{domxref("Document.doctype")}} {{readonlyinline}}
- 回傳目前文件的 Document Type Definition(DTD)。
- {{domxref("Document.documentElement")}} {{readonlyinline}}
- 回傳當前文件 {{domxref("Document")}} 的根元素。以 HTML documents為例:它會回傳 {{HTMLElement("html")}} 這項元素。
- {{domxref("Document.documentURI")}} {{readonlyinline}}
- Returns the document location as a string.
- {{domxref("Document.domConfig")}} {{Deprecated_inline}}
- Should return a {{domxref("DOMConfiguration")}} object.
- {{domxref("Document.fullscreen")}} {{Deprecated_Inline}}
- true
when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
- {{domxref("Document.hidden")}} {{readonlyinline}}
- …
- {{domxref("Document.implementation")}} {{readonlyinline}}
- Returns the DOM implementation associated with the current document.
- {{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
- Alias of {{domxref("Document.characterSet")}}. Use this property instead.
- {{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
- Returns the name of the style sheet set that was last enabled. Has the value null
until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
- {{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}}
- Returns a {{jsxref("Boolean")}} that is true
only if this document is synthetic, such as a standalone image, video, audio file, or the like.
- {{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}}
- The element that's currently in full screen mode for this document.
- {{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}}
- true
if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
- {{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
- Returns the element set as the target for mouse events while the pointer is locked. null
if lock is pending, pointer is unlocked, or if the target is in another document.
- {{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
- Returns the preferred style sheet set as specified by the page author.
- {{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
- Returns a reference to the {{domxref("Element")}} that scrolls the document.
- {{domxref("Document.selectedStyleSheetSet")}}
- Returns which style sheet set is currently in use.
- {{domxref("Document.styleSheets")}} {{readonlyinline}}
- Returns a list of the style sheet objects on the current document.
- {{domxref("Document.styleSheetSets")}} {{readonlyinline}}
- Returns a list of the style sheet sets available on the document.
- {{domxref("Document.timeline")}} {{readonlyinline}}
- …
- {{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
- …
- {{domxref("Document.visibilityState")}} {{readonlyinline}}
-
- Returns a string
denoting the visibility state of the document. Possible values are visible
, hidden
, prerender
, and unloaded
.
-
- {{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
- Returns the encoding as determined by the XML declaration.
- {{domxref("Document.xmlStandalone")}} {{Deprecated_Inline}}
- Returns true
if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false
.
- {{domxref("Document.xmlVersion")}} {{Deprecated_Inline}}
- Returns the version number as specified in the XML declaration or "1.0"
if the declaration is absent.
-
-
-The Document
interface is extended with the {{domxref("ParentNode")}} interface:
-
-{{page("/en-US/docs/Web/API/ParentNode","Properties")}}
-
-HTML 文件擴充
-
-window.document
物件的部分屬性繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 Document
從 HTML5 之後擴充的屬性。
-
-
- {{domxref("Document.activeElement")}} {{readonlyinline}}
- Returns the currently focused element.
- {{domxref("Document.alinkColor")}} {{Deprecated_inline}}
- Returns or sets the color of active links in the document body.
- {{domxref("Document.anchors")}}
- Returns a list of all of the anchors in the document.
- {{domxref("Document.applets")}} {{Deprecated_inline}}
- Returns an ordered list of the applets within a document.
- {{domxref("Document.bgColor")}} {{Deprecated_inline}}
- Gets/sets the background color of the current document.
- {{domxref("Document.body")}}
- Returns the {{HTMLElement("body")}} element of the current document.
- {{domxref("Document.cookie")}}
- Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
- {{domxref("Document.defaultView")}} {{readonlyinline}}
- Returns a reference to the window object.
- {{domxref("Document.designMode")}}
- Gets/sets the ability to edit the whole document.
- {{domxref("Document.dir")}} {{readonlyinline}}
- Gets/sets directionality (rtl/ltr) of the document.
- {{domxref("Document.domain")}} {{readonlyinline}}
- Returns the domain of the current document.
- {{domxref("Document.embeds")}} {{readonlyinline}}
- Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
- {{domxref("document.fgColor")}} {{Deprecated_inline}}
- Gets/sets the foreground color, or text color, of the current document.
- {{domxref("Document.forms")}} {{readonlyinline}}
- Returns a list of the {{HTMLElement("form")}} elements within the current document.
- {{domxref("Document.head")}} {{readonlyinline}}
- Returns the {{HTMLElement("head")}} element of the current document.
- {{domxref("Document.height")}} {{non-standard_inline}} {{Deprecated_Inline}}
- Gets/sets the height of the current document.
- {{domxref("Document.images")}} {{readonlyinline}}
- Returns a list of the images in the current document.
- {{domxref("Document.lastModified")}} {{readonlyinline}}
- Returns the date on which the document was last modified.
- {{domxref("Document.linkColor")}} {{Deprecated_inline}}
- Gets/sets the color of hyperlinks in the document.
- {{domxref("Document.links")}} {{readonlyinline}}
- Returns a list of all the hyperlinks in the document.
- {{domxref("Document.location")}} {{readonlyinline}}
- Returns the URI of the current document.
- {{domxref("Document.plugins")}} {{readonlyinline}}
- Returns a list of the available plugins.
- {{domxref("Document.readyState")}} {{readonlyinline}}
- Returns loading status of the document.
- {{domxref("Document.referrer")}} {{readonlyinline}}
- Returns the URI of the page that linked to this page.
- {{domxref("Document.scripts")}} {{readonlyinline}}
- Returns all the {{HTMLElement("script")}} elements on the document.
- {{domxref("Document.title")}}
- Sets or gets title of the current document.
- {{domxref("Document.URL")}} {{readonlyInline}}
- Returns the document location as a string.
- {{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
- Gets/sets the color of visited hyperlinks.
- {{domxref("Document.width")}} {{non-standard_inline}} {{Deprecated_Inline}}
- Returns the width of the current document.
-
-
-事件處理器
-
-
- {{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("afterscriptexecute")}} event.
- {{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("beforescriptexecute")}} event.
- {{domxref("Document.oncopy")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("copy")}} event.
- {{domxref("Document.oncut")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("cut")}} event.
- {{domxref("Document.onfullscreenchange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
- {{domxref("Document.onfullscreenerror")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
- {{domxref("Document.onpaste")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("paste")}} event.
- {{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
- Represents the event handling code for the {{event("pointerlockchange")}} event.
- {{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
- Represetnts the event handling code for the {{event("pointerlockerror")}} event.
- {{domxref("Document.onreadystatechange")}}
- Represents the event handling code for the {{event("readystatechange")}} event.
- {{domxref("Document.onselectionchange")}} {{experimental_inline}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
- {{domxref("Document.onwheel")}} {{non-standard_inline}}
- Represents the event handling code for the {{event("wheel")}} event.
-
-
-此介面繼承了 {{domxref("GlobalEventHandlers")}} 的事件處理器:
-
-{{Page("/zh-TW/docs/Web/API/GlobalEventHandlers", "屬性")}}
-
-方法
-
-This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.
-
-
- {{domxref("Document.adoptNode()")}}
- Adopt node from an external document.
- {{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
- See {{domxref("Window.captureEvents")}}.
- {{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
- Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
- {{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
- Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
- {{domxref("Document.createAttribute()")}}
- Creates a new {{domxref("Attr")}} object and returns it.
- {{domxref("Document.createAttributeNS()")}}
- Creates a new attribute node in a given namespace and returns it.
- {{domxref("Document.createCDATASection()")}}
- Creates a new CDATA node and returns it.
- {{domxref("Document.createComment()")}}
- Creates a new comment node and returns it.
- {{domxref("Document.createDocumentFragment()")}}
- Creates a new document fragment.
- {{domxref("Document.createElement()")}}
- Creates a new element with the given tag name.
- {{domxref("Document.createElementNS()")}}
- Creates a new element with the given tag name and namespace URI.
- {{domxref("Document.createEntityReference()")}} {{Deprecated_Inline}}
- Creates a new entity reference object and returns it.
- {{domxref("Document.createEvent()")}}
- Creates an event object.
- {{domxref("Document.createNodeIterator()")}}
- Creates a {{domxref("NodeIterator")}} object.
- {{domxref("Document.createProcessingInstruction()")}}
- Creates a new {{domxref("ProcessingInstruction")}} object.
- {{domxref("Document.createRange()")}}
- Creates a {{domxref("Range")}} object.
- {{domxref("Document.createTextNode()")}}
- Creates a text node.
- {{domxref("Document.createTouch()")}}
- Creates a {{domxref("Touch")}} object.
- {{domxref("Document.createTouchList()")}}
- Creates a {{domxref("TouchList")}} object.
- {{domxref("Document.createTreeWalker()")}}
- Creates a {{domxref("TreeWalker")}} object.
- {{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
- Returns the topmost element at the specified coordinates.
- {{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
- Returns an array of all elements at the specified coordinates.
- {{domxref("Document.enableStyleSheetsForSet()")}}
- Enables the style sheets for the specified style sheet set.
- {{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
- Release the pointer lock.
- {{domxref("Document.getAnimations()")}} {{experimental_inline}}
- Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the document
.
- {{domxref("Document.getElementsByClassName()")}}
- Returns a list of elements with the given class name.
- {{domxref("Document.getElementsByTagName()")}}
- Returns a list of elements with the given tag name.
- {{domxref("Document.getElementsByTagNameNS()")}}
- Returns a list of elements with the given tag name and namespace.
- {{domxref("Document.importNode()")}}
- Returns a clone of a node from an external document.
- {{domxref("Document.normalizeDocument()")}} {{Deprecated_Inline}}
- Replaces entities, normalizes text nodes, etc.
- {{domxref("Document.registerElement()")}} {{experimental_inline}}
- Registers a web component.
- {{domxref("Document.releaseCapture()")}} {{non-standard_inline}}
- Releases the current mouse capture if it's on an element in this document.
- {{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
- See {{domxref("Window.releaseEvents()")}}.
- {{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{Deprecated_Inline}}
- See {{domxref("Window.routeEvent()")}}.
- {{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}}
- Allows you to change the element being used as the background image for a specified element ID.
-
-
-The Document
interface is extended with the {{domxref("ParentNode")}} interface:
-
-
- {{domxref("document.getElementById","document.getElementById(String id)")}}
- Returns an object reference to the identified element.
- {{domxref("document.querySelector","document.querySelector(String selector)")}}
- Returns the first Element node within the document, in document order, that matches the specified selectors.
- {{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}}
- Returns a list of all the Element nodes within the document that match the specified selectors.
-
-
-The Document
interface is extended with the {{domxref("XPathEvaluator")}} interface:
-
-
- {{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
- Compiles an XPathExpression
which can then be used for (repeated) evaluations.
- {{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
- Creates an {{domxref("XPathNSResolver")}} object.
- {{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
- Evaluates an XPath expression.
-
-
-HTML 文件擴充
-
-Document
物件的部分方法繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 Document
從 HTML5 之後擴充的方法:
-
-
- {{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
- In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
- {{domxref("document.close()")}}
- Closes a document stream for writing.
- {{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
- On an editable document, executes a formating command.
- {{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
- Returns a list of elements with the given name.
- {{domxref("document.getSelection()")}}
- Returns a {{domxref("Selection")}} object related to text selected in the document.
- {{domxref("document.hasFocus()")}}
- Returns true
if the focus is currently located anywhere inside the specified document.
- {{domxref("document.open()")}}
- Opens a document stream for writing.
- {{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
- Returns true if the formating command can be executed on the current range.
- {{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
- Returns true if the formating command is in an indeterminate state on the current range.
- {{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
- Returns true if the formating command has been executed on the current range.
- {{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
- Returns true if the formating command is supported on the current range.
- {{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
- Returns the current value of the current range for a formating command.
- {{domxref("document.write","document.write(String text)")}}
- Writes text in a document.
- {{domxref("document.writeln","document.writeln(String text)")}}
- Writes a line of text in a document.
-
-
-規範
+{{APIRef}}
+
+**`Document`** 介面代表所有在瀏覽器中載入的網頁,也是作為網頁內容 [DOM 樹](/zh-TW/docs/Using_the_W3C_DOM_Level_1_Core)(包含如 {{HTMLElement("body")}}、{{HTMLElement("table")}} 與其它的{{domxref("Element", "元素")}})的進入點。`Document` 提供了網頁文件所需的通用函式,例如取得頁面 URL 或是建立網頁文件中新的元素節點等。
+
+{{inheritanceDiagram}}
+
+`Document` 介面描述了各種類型文件的共同屬性與方法。根據文件的類型(如 [HTML](/zh-TW/docs/HTML)、[XML](/zh-TW/docs/XML)、SVG 等),也會擁有各自的 API:HTML 文件(content type 為 `text/html`)實作了 {{domxref("HTMLDocument")}} 介面,而 XML 及 SVG 文件實作了 {{domxref("XMLDocument")}} 介面。
+
+請注意 `window.document` 物件為 `HTMLDocument` 所建構。
+
+## 屬性
+
+_這個介面繼承了 {{domxref("Node")}} 以及 {{domxref("EventTarget")}} 介面。_
+
+- {{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+ - : Provides access to all elements with an `id`. This is a legacy, non-standard interface and you should use the {{domxref("document.getElementById()")}} method instead.
+- {{domxref("Document.async")}} {{Deprecated_inline}}
+ - : Used with {{domxref("Document.load")}} to indicate an asynchronous request.
+- {{domxref("Document.characterSet")}} {{readonlyinline}}
+ - : Returns the character set being used by the document.
+- {{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+ - : Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+- {{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
+ - : Indicates whether the document is rendered in _quirks_ or _strict_ mode.
+- {{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
+ - : Returns the Content-Type from the MIME Header of the current document.
+- {{domxref("Document.doctype")}} {{readonlyinline}}
+ - : 回傳目前文件的 Document Type Definition(DTD)。
+- {{domxref("Document.documentElement")}} {{readonlyinline}}
+ - : 回傳當前文件 {{domxref("Document")}} 的根元素。以 HTML documents 為例:它會回傳 {{HTMLElement("html")}} 這項元素。
+- {{domxref("Document.documentURI")}} {{readonlyinline}}
+ - : Returns the document location as a string.
+- {{domxref("Document.domConfig")}} {{Deprecated_inline}}
+ - : Should return a {{domxref("DOMConfiguration")}} object.
+- {{domxref("Document.fullscreen")}} {{Deprecated_Inline}}
+ - : `true` when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+- {{domxref("Document.hidden")}} {{readonlyinline}}
+ - : …
+- {{domxref("Document.implementation")}} {{readonlyinline}}
+ - : Returns the DOM implementation associated with the current document.
+- {{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+ - : Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+- {{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
+ - : Returns the name of the style sheet set that was last enabled. Has the value `null` until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+- {{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}}
+ - : Returns a {{jsxref("Boolean")}} that is `true` only if this document is synthetic, such as a standalone image, video, audio file, or the like.
+- {{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}}
+ - : The element that's currently in full screen mode for this document.
+- {{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}}
+ - : `true` if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
+- {{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+ - : Returns the element set as the target for mouse events while the pointer is locked. `null` if lock is pending, pointer is unlocked, or if the target is in another document.
+- {{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+ - : Returns the preferred style sheet set as specified by the page author.
+- {{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
+ - : Returns a reference to the {{domxref("Element")}} that scrolls the document.
+- {{domxref("Document.selectedStyleSheetSet")}}
+ - : Returns which style sheet set is currently in use.
+- {{domxref("Document.styleSheets")}} {{readonlyinline}}
+ - : Returns a list of the style sheet objects on the current document.
+- {{domxref("Document.styleSheetSets")}} {{readonlyinline}}
+ - : Returns a list of the style sheet sets available on the document.
+- {{domxref("Document.timeline")}} {{readonlyinline}}
+ - : …
+- {{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
+ - : …
+- {{domxref("Document.visibilityState")}} {{readonlyinline}}
+ - : Returns a `string` denoting the visibility state of the document. Possible values are `visible`, `hidden`, `prerender`, and `unloaded`.
+- {{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+ - : Returns the encoding as determined by the XML declaration.
+- {{domxref("Document.xmlStandalone")}} {{Deprecated_Inline}}
+ - : Returns `true` if the XML declaration specifies the document to be standalone (_e.g.,_ An external part of the DTD affects the document's content), else `false`.
+- {{domxref("Document.xmlVersion")}} {{Deprecated_Inline}}
+ - : Returns the version number as specified in the XML declaration or `"1.0"` if the declaration is absent.
+
+The `Document` interface is extended with the {{domxref("ParentNode")}} interface:
+
+{{page("/en-US/docs/Web/API/ParentNode","Properties")}}
+
+### HTML 文件擴充
+
+_**`window.document`** 物件的部分屬性繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 `Document` 從 HTML5 之後擴充的屬性。_
+
+- {{domxref("Document.activeElement")}} {{readonlyinline}}
+ - : Returns the currently focused element.
+- {{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+ - : Returns or sets the color of active links in the document body.
+- {{domxref("Document.anchors")}}
+ - : Returns a list of all of the anchors in the document.
+- {{domxref("Document.applets")}} {{Deprecated_inline}}
+ - : Returns an ordered list of the applets within a document.
+- {{domxref("Document.bgColor")}} {{Deprecated_inline}}
+ - : Gets/sets the background color of the current document.
+- {{domxref("Document.body")}}
+ - : Returns the {{HTMLElement("body")}} element of the current document.
+- {{domxref("Document.cookie")}}
+ - : Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+- {{domxref("Document.defaultView")}} {{readonlyinline}}
+ - : Returns a reference to the window object.
+- {{domxref("Document.designMode")}}
+ - : Gets/sets the ability to edit the whole document.
+- {{domxref("Document.dir")}} {{readonlyinline}}
+ - : Gets/sets directionality (rtl/ltr) of the document.
+- {{domxref("Document.domain")}} {{readonlyinline}}
+ - : Returns the domain of the current document.
+- {{domxref("Document.embeds")}} {{readonlyinline}}
+ - : Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+- {{domxref("document.fgColor")}} {{Deprecated_inline}}
+ - : Gets/sets the foreground color, or text color, of the current document.
+- {{domxref("Document.forms")}} {{readonlyinline}}
+ - : Returns a list of the {{HTMLElement("form")}} elements within the current document.
+- {{domxref("Document.head")}} {{readonlyinline}}
+ - : Returns the {{HTMLElement("head")}} element of the current document.
+- {{domxref("Document.height")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Gets/sets the height of the current document.
+- {{domxref("Document.images")}} {{readonlyinline}}
+ - : Returns a list of the images in the current document.
+- {{domxref("Document.lastModified")}} {{readonlyinline}}
+ - : Returns the date on which the document was last modified.
+- {{domxref("Document.linkColor")}} {{Deprecated_inline}}
+ - : Gets/sets the color of hyperlinks in the document.
+- {{domxref("Document.links")}} {{readonlyinline}}
+ - : Returns a list of all the hyperlinks in the document.
+- {{domxref("Document.location")}} {{readonlyinline}}
+ - : Returns the URI of the current document.
+- {{domxref("Document.plugins")}} {{readonlyinline}}
+ - : Returns a list of the available plugins.
+- {{domxref("Document.readyState")}} {{readonlyinline}}
+ - : Returns loading status of the document.
+- {{domxref("Document.referrer")}} {{readonlyinline}}
+ - : Returns the URI of the page that linked to this page.
+- {{domxref("Document.scripts")}} {{readonlyinline}}
+ - : Returns all the {{HTMLElement("script")}} elements on the document.
+- {{domxref("Document.title")}}
+ - : Sets or gets title of the current document.
+- {{domxref("Document.URL")}} {{readonlyInline}}
+ - : Returns the document location as a string.
+- {{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+ - : Gets/sets the color of visited hyperlinks.
+- {{domxref("Document.width")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Returns the width of the current document.
+
+### 事件處理器
+
+- {{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("afterscriptexecute")}} event.
+- {{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("beforescriptexecute")}} event.
+- {{domxref("Document.oncopy")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("copy")}} event.
+- {{domxref("Document.oncut")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("cut")}} event.
+- {{domxref("Document.onfullscreenchange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+- {{domxref("Document.onfullscreenerror")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+- {{domxref("Document.onpaste")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("paste")}} event.
+- {{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
+ - : Represents the event handling code for the {{event("pointerlockchange")}} event.
+- {{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+ - : Represetnts the event handling code for the {{event("pointerlockerror")}} event.
+- {{domxref("Document.onreadystatechange")}}
+ - : Represents the event handling code for the {{event("readystatechange")}} event.
+- {{domxref("Document.onselectionchange")}} {{experimental_inline}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+- {{domxref("Document.onwheel")}} {{non-standard_inline}}
+ - : Represents the event handling code for the {{event("wheel")}} event.
+
+_此介面繼承了 {{domxref("GlobalEventHandlers")}} 的事件處理器:_
+
+{{Page("/zh-TW/docs/Web/API/GlobalEventHandlers", "屬性")}}
+
+## 方法
+
+_This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces._
+
+- {{domxref("Document.adoptNode()")}}
+ - : Adopt node from an external document.
+- {{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+ - : See {{domxref("Window.captureEvents")}}.
+- {{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
+ - : Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
+- {{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+ - : Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
+- {{domxref("Document.createAttribute()")}}
+ - : Creates a new {{domxref("Attr")}} object and returns it.
+- {{domxref("Document.createAttributeNS()")}}
+ - : Creates a new attribute node in a given namespace and returns it.
+- {{domxref("Document.createCDATASection()")}}
+ - : Creates a new CDATA node and returns it.
+- {{domxref("Document.createComment()")}}
+ - : Creates a new comment node and returns it.
+- {{domxref("Document.createDocumentFragment()")}}
+ - : Creates a new document fragment.
+- {{domxref("Document.createElement()")}}
+ - : Creates a new element with the given tag name.
+- {{domxref("Document.createElementNS()")}}
+ - : Creates a new element with the given tag name and namespace URI.
+- {{domxref("Document.createEntityReference()")}} {{Deprecated_Inline}}
+ - : Creates a new entity reference object and returns it.
+- {{domxref("Document.createEvent()")}}
+ - : Creates an event object.
+- {{domxref("Document.createNodeIterator()")}}
+ - : Creates a {{domxref("NodeIterator")}} object.
+- {{domxref("Document.createProcessingInstruction()")}}
+ - : Creates a new {{domxref("ProcessingInstruction")}} object.
+- {{domxref("Document.createRange()")}}
+ - : Creates a {{domxref("Range")}} object.
+- {{domxref("Document.createTextNode()")}}
+ - : Creates a text node.
+- {{domxref("Document.createTouch()")}}
+ - : Creates a {{domxref("Touch")}} object.
+- {{domxref("Document.createTouchList()")}}
+ - : Creates a {{domxref("TouchList")}} object.
+- {{domxref("Document.createTreeWalker()")}}
+ - : Creates a {{domxref("TreeWalker")}} object.
+- {{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
+ - : Returns the topmost element at the specified coordinates.
+- {{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
+ - : Returns an array of all elements at the specified coordinates.
+- {{domxref("Document.enableStyleSheetsForSet()")}}
+ - : Enables the style sheets for the specified style sheet set.
+- {{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+ - : Release the pointer lock.
+- {{domxref("Document.getAnimations()")}} {{experimental_inline}}
+ - : Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the `document`.
+- {{domxref("Document.getElementsByClassName()")}}
+ - : Returns a list of elements with the given class name.
+- {{domxref("Document.getElementsByTagName()")}}
+ - : Returns a list of elements with the given tag name.
+- {{domxref("Document.getElementsByTagNameNS()")}}
+ - : Returns a list of elements with the given tag name and namespace.
+- {{domxref("Document.importNode()")}}
+ - : Returns a clone of a node from an external document.
+- {{domxref("Document.normalizeDocument()")}} {{Deprecated_Inline}}
+ - : Replaces entities, normalizes text nodes, etc.
+- {{domxref("Document.registerElement()")}} {{experimental_inline}}
+ - : Registers a web component.
+- {{domxref("Document.releaseCapture()")}} {{non-standard_inline}}
+ - : Releases the current mouse capture if it's on an element in this document.
+- {{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+ - : See {{domxref("Window.releaseEvents()")}}.
+- {{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : See {{domxref("Window.routeEvent()")}}.
+- {{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}}
+ - : Allows you to change the element being used as the background image for a specified element ID.
+
+The `Document` interface is extended with the {{domxref("ParentNode")}} interface:
+
+- {{domxref("document.getElementById","document.getElementById(String id)")}}
+ - : Returns an object reference to the identified element.
+- {{domxref("document.querySelector","document.querySelector(String selector)")}}
+ - : Returns the first Element node within the document, in document order, that matches the specified selectors.
+- {{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}}
+ - : Returns a list of all the Element nodes within the document that match the specified selectors.
+
+The `Document` interface is extended with the {{domxref("XPathEvaluator")}} interface:
+
+- {{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
+ - : Compiles an [`XPathExpression`](/en-US/docs/XPathExpression) which can then be used for (repeated) evaluations.
+- {{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
+ - : Creates an {{domxref("XPathNSResolver")}} object.
+- {{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+ - : Evaluates an XPath expression.
+
+### HTML 文件擴充
+
+`Document` 物件的部分方法繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 `Document` 從 HTML5 之後擴充的方法:
+
+- {{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+ - : In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+- {{domxref("document.close()")}}
+ - : Closes a document stream for writing.
+- {{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
+ - : On an editable document, executes a formating command.
+- {{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
+ - : Returns a list of elements with the given name.
+- {{domxref("document.getSelection()")}}
+ - : Returns a {{domxref("Selection")}} object related to text selected in the document.
+- {{domxref("document.hasFocus()")}}
+ - : Returns `true` if the focus is currently located anywhere inside the specified document.
+- {{domxref("document.open()")}}
+ - : Opens a document stream for writing.
+- {{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
+ - : Returns true if the formating command can be executed on the current range.
+- {{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
+ - : Returns true if the formating command is in an indeterminate state on the current range.
+- {{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
+ - : Returns true if the formating command has been executed on the current range.
+- {{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
+ - : Returns true if the formating command is supported on the current range.
+- {{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
+ - : Returns the current value of the current range for a formating command.
+- {{domxref("document.write","document.write(String text)")}}
+ - : Writes text in a document.
+- {{domxref("document.writeln","document.writeln(String text)")}}
+ - : Writes a line of text in a document.
+
+## 規範
{{Specifications}}
-瀏覽器相容性備註
-
-Firefox notes
-
-Mozilla defines a set of non-standard properties made only for XUL content:
-
-
- {{domxref("document.currentScript")}} {{non-standard_inline}}
- Returns the {{HTMLElement("script")}} element that is currently executing.
- {{domxref("document.documentURIObject")}}
- (Mozilla add-ons only! ) Returns the nsIURI
object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
- {{domxref("document.popupNode")}}
- Returns the node upon which a popup was invoked.
- {{domxref("document.tooltipNode")}}
- Returns the node which is the target of the current tooltip.
-
-
-Mozilla also define some non-standard methods:
-
-
- {{domxref("document.execCommandShowHelp")}} {{Deprecated_Inline}}
- This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
- {{domxref("document.getBoxObjectFor")}} {{Deprecated_Inline}}
- Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
- {{domxref("document.loadOverlay")}}
- Loads a XUL overlay dynamically. This only works in XUL documents.
- {{domxref("document.queryCommandText")}} {{Deprecated_Inline}}
- This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
-
-
-Internet Explorer notes
-
-Microsoft defines some non-standard properties:
-
-
- {{domxref("document.fileSize")}}* {{non-standard_inline}} {{Deprecated_Inline}}
- Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN . Internet Explorer does not support all methods from the Node
interface in the Document
interface:
- {{domxref("document.contains")}}
- As a work-around, document.body.contains()
can be used.
-
+## 瀏覽器相容性備註
+
+### Firefox notes
+
+Mozilla defines a set of non-standard properties made only for XUL content:
+
+- {{domxref("document.currentScript")}} {{non-standard_inline}}
+ - : Returns the {{HTMLElement("script")}} element that is currently executing.
+- {{domxref("document.documentURIObject")}}
+ - : (**Mozilla add-ons only!**) Returns the `nsIURI` object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+- {{domxref("document.popupNode")}}
+ - : Returns the node upon which a popup was invoked.
+- {{domxref("document.tooltipNode")}}
+ - : Returns the node which is the target of the current tooltip.
+
+Mozilla also define some non-standard methods:
+
+- {{domxref("document.execCommandShowHelp")}} {{Deprecated_Inline}}
+ - : This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+- {{domxref("document.getBoxObjectFor")}} {{Deprecated_Inline}}
+ - : Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+- {{domxref("document.loadOverlay")}}
+ - : Loads a [XUL overlay](/zh-TW/docs/XUL_Overlays) dynamically. This only works in XUL documents.
+- {{domxref("document.queryCommandText")}} {{Deprecated_Inline}}
+ - : This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+### Internet Explorer notes
+
+Microsoft defines some non-standard properties:
+
+- {{domxref("document.fileSize")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See [MSDN](http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx). Internet Explorer does not support all methods from the `Node` interface in the `Document` interface:
+- {{domxref("document.contains")}}
+ - : As a work-around, `document.body.contains()` can be used.
diff --git a/files/zh-tw/web/api/document/registerelement/index.md b/files/zh-tw/web/api/document/registerelement/index.md
index baed447e961f3e..c7c94debfe560a 100644
--- a/files/zh-tw/web/api/document/registerelement/index.md
+++ b/files/zh-tw/web/api/document/registerelement/index.md
@@ -8,56 +8,52 @@ tags:
- 自訂標籤
translation_of: Web/API/Document/registerElement
---
-{{APIRef("DOM")}}{{Deprecated_header}}
+{{APIRef("DOM")}}{{Deprecated_header}}
-
+> **警告:** document.registerElement() 已經被棄用,建議使用 [customElements.define()](/zh-TW/docs/Web/API/CustomElementRegistry/define).
-document.registerElement()
可以在瀏覽器中註冊一個新的自訂標籤(元素)and returns a constructor for the new element.
+**`document.registerElement()`** 可以在瀏覽器中註冊一個新的自訂標籤(元素)and returns a constructor for the new element.
-
+> **備註:** This is an experimental technology. The browser you use it in must support Web Components. See [Enabling Web Components in Firefox](/zh-TW/docs/Web/Web_Components#Enabling_Web_Components_in_Firefox).
-語法
+## 語法
-var constructor = document.registerElement(tag-name , options );
+```plain
+var constructor = document.registerElement(tag-name, options);
+```
-參數
+### 參數
-
- 標籤名稱
- 自訂的標籤名稱需有一個 橫線 ( - ), 例如my-tag
.
- options {{optional_inline}}
-
- An object with properties prototype to base the custom element on, and extends , an existing tag to extend. Both of these are optional.
-
-
+- _標籤名稱_
+ - : 自訂的標籤名稱需有一個 橫線 ( - ), 例如`my-tag`.
+- _options {{optional_inline}}_
+ - : An object with properties **prototype** to base the custom element on, and **extends**, an existing tag to extend. Both of these are optional.
-例子
+## 例子
-這是一個非常簡單的例子:
+這是一個非常簡單的例子:
-var Mytag = document.registerElement('my-tag');
-
+```js
+var Mytag = document.registerElement('my-tag');
+```
-現在新的標籤已經在瀏覽器中註冊了. The Mytag
variable holds a constructor that you can use to create a my-tag
element in the document as follows:
+現在新的標籤已經在瀏覽器中註冊了. The `Mytag` variable holds a constructor that you can use to create a `my-tag` element in the document as follows:
-document.body.appendChild(new Mytag());
+```js
+document.body.appendChild(new Mytag());
+```
-This inserts an empty my-tag
element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. Here is one way to add content to the new tag:
+This inserts an empty `my-tag` element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. Here is one way to add content to the new tag:
-var mytag = document.getElementsByTagName("my-tag")[0];
+```js
+var mytag = document.getElementsByTagName("my-tag")[0];
mytag.textContent = "I am a my-tag element.";
-
+```
-瀏覽器支援性
+## 瀏覽器支援性
{{Compat("api.Document.registerElement")}}
-也看一下
+## 也看一下
-
+- [Custom Elements](/zh-TW/docs/Web/Web_Components/Custom_Elements)
diff --git a/files/zh-tw/web/api/document/width/index.md b/files/zh-tw/web/api/document/width/index.md
index 9bd2f13e470769..6d2c1ddafa68c0 100644
--- a/files/zh-tw/web/api/document/width/index.md
+++ b/files/zh-tw/web/api/document/width/index.md
@@ -3,43 +3,42 @@ title: Document.width
slug: Web/API/Document/width
translation_of: Web/API/Document/width
---
-{{APIRef("DOM")}} {{deprecated_header}}
+{{APIRef("DOM")}} {{deprecated_header}}
-
-
注意: 從 {{Gecko("6.0")}} 開始, document.width 將不再被支援。取而代之的是
document.body.clientWidth 。請參照:
{{domxref("element.clientWidth")}}.
-
+> **備註:** 從 {{Gecko("6.0")}} 開始, ` document.width 將不再被支援。取而代之的是 `` document.body.clientWidth 。請參照: `{{domxref("element.clientWidth")}}.
-傳回目前文件中,{{HTMLElement("body")}} 元素的寬度有多少像素。
+傳回目前文件中,{{HTMLElement("body")}} 元素的寬度有多少像素。
-Internet Explorer 不支援!
+Internet Explorer 不支援!
-語法
+## 語法
-pixels = document.width;
-
+```js
+pixels = document.width;
+```
-範例
+## 範例
-function init() {
+```js
+function init() {
alert("文件的寬度是 " + document.width + " 像素。");
}
-
+```
-其他替代
+## 其他替代
-document.body.clientWidth /* <body> 的寬度 */
-document.documentElement.clientWidth /* <html> 的寬度 */
+```js
+document.body.clientWidth /* 的寬度 */
+document.documentElement.clientWidth /* 的寬度 */
window.innerWidth /* 視窗的寬度 */
-
+```
-規範於
+## 規範於
-HTML5
+HTML5
-同時參考
+## 同時參考
-
- {{domxref("document.height")}}
- {{domxref("Element.clientWidth")}}
- {{domxref("Element.scrollWidth")}}
-
+- {{domxref("document.height")}}
+- {{domxref("Element.clientWidth")}}
+- {{domxref("Element.scrollWidth")}}
diff --git a/files/zh-tw/web/api/document_object_model/index.md b/files/zh-tw/web/api/document_object_model/index.md
index 1e96d13dcada0e..b51644699ada0c 100644
--- a/files/zh-tw/web/api/document_object_model/index.md
+++ b/files/zh-tw/web/api/document_object_model/index.md
@@ -8,377 +8,333 @@ tags:
- Intermediate
translation_of: Web/API/Document_Object_Model
---
-{{DefaultAPISidebar("DOM")}}
-
-文件物件模型(Document Object Model, DOM ) 是 HTML、XML 和 SVG 文件的程式介面。它提供了一個文件(樹)的結構化表示法,並定義讓程式可以存取並改變文件架構、風格和內容的方法。DOM 提供了文件以擁有屬性與函式的節點與物件組成的結構化表示。節點也可以附加事件處理程序,一旦觸發事件就會執行處理程序。 本質上,它將網頁與腳本或程式語言連結在一起。
-
-雖然常常使用 JavaScript 來存取 DOM,但它本身並不是 JavaScript 語言的一部分,而且它也可以被其他語言存取(雖然不太常見就是了)。
-
-這裡有一篇 DOM 的介紹 可供查閱。
-
-DOM 介面
-
-
-
- {{domxref("Attr")}}
- {{domxref("CharacterData")}}
- {{domxref("ChildNode")}} {{experimental_inline}}
- {{domxref("Comment")}}
- {{domxref("CustomEvent")}}
- {{domxref("Document")}}
- {{domxref("DocumentFragment")}}
- {{domxref("DocumentType")}}
- {{domxref("DOMError")}}
- {{domxref("DOMException")}}
- {{domxref("DOMImplementation")}}
- {{domxref("DOMString")}}
- {{domxref("DOMTimeStamp")}}
- {{domxref("DOMSettableTokenList")}}
- {{domxref("DOMStringList")}}
- {{domxref("DOMTokenList")}}
- {{domxref("Element")}}
- {{domxref("Event")}}
- {{domxref("EventTarget")}}
- {{domxref("HTMLCollection")}}
- {{domxref("MutationObserver")}}
- {{domxref("MutationRecord")}}
- {{domxref("Node")}}
- {{domxref("NodeFilter")}}
- {{domxref("NodeIterator")}}
- {{domxref("NodeList")}}
- {{domxref("ParentNode")}} {{experimental_inline}}
- {{domxref("ProcessingInstruction")}}
- {{domxref("Range")}}
- {{domxref("Text")}}
- {{domxref("TreeWalker")}}
- {{domxref("URL")}}
- {{domxref("Window")}}
- {{domxref("Worker")}}
- {{domxref("XMLDocument")}} {{experimental_inline}}
-
-
-
-棄用的 DOM 介面
-
-文件物件模型正被大量的簡化。為了達成這個目的,下這些介面是在 DOM level 3 或更早的規範中就被刪掉了。由於不清楚是否會被再度納入,請姑且當他們已經被遺棄,並避免使用:
-
-
-
- {{domxref("CDATASection")}}
- {{domxref("DOMConfiguration")}}
- {{domxref("DOMErrorHandler")}}
- {{domxref("DOMImplementationList")}}
- {{domxref("DOMImplementationRegistry")}}
- {{domxref("DOMImplementationSource")}}
- {{domxref("DOMLocator")}}
- {{domxref("DOMObject")}}
- {{domxref("DOMUserData")}}
- {{domxref("Entity")}}
- {{domxref("EntityReference")}}
- {{domxref("NamedNodeMap")}}
- {{domxref("NameList")}}
- {{domxref("Notation")}}
- {{domxref("TypeInfo")}}
- {{domxref("UserDataHandler")}}
-
-
-
-
-HTML 介面
-
-一份包含 html 的文件會透過 {{domxref("HTMLDocument")}} 介面來描述。注意 HTML 規範也擴展了 {{domxref("Document")}} 介面。
-
-HTMLDocument
物件也提供了瀏覽器功能的存取:分頁、透過 {{domxref("Window")}} 介面描繪頁面的視窗、與其相關的 {{domxref("window.style", "樣式")}} (通常是 CSS )、與本文關聯的瀏覽器 {{domxref("window.history", "歷史")}}、以及一個文件內的 {{domxref("Selection", "選擇器")}}。
-
-HTML 元素介面
-
-
-
- {{domxref("HTMLAnchorElement")}}
- {{domxref("HTMLAppletElement")}}
- {{domxref("HTMLAreaElement")}}
- {{domxref("HTMLAudioElement")}}
- {{domxref("HTMLBaseElement")}}
- {{domxref("HTMLBodyElement")}}
- {{domxref("HTMLBRElement")}}
- {{domxref("HTMLButtonElement")}}
- {{domxref("HTMLCanvasElement")}}
- {{domxref("HTMLDataElement")}}
- {{domxref("HTMLDataListElement")}}
- {{domxref("HTMLDialogElement")}}
- {{domxref("HTMLDirectoryElement")}}
- {{domxref("HTMLDivElement")}}
- {{domxref("HTMLDListElement")}}
- {{domxref("HTMLElement")}}
- {{domxref("HTMLEmbedElement")}}
- {{domxref("HTMLFieldSetElement")}}
- {{domxref("HTMLFontElement")}}
- {{domxref("HTMLFormElement")}}
- {{domxref("HTMLFrameElement")}}
- {{domxref("HTMLFrameSetElement")}}
- {{domxref("HTMLHeadElement")}}
- {{domxref("HTMLHeadingElement")}}
- {{domxref("HTMLHtmlElement")}}
- {{domxref("HTMLHRElement")}}
- {{domxref("HTMLIFrameElement")}}
- {{domxref("HTMLImageElement")}}
- {{domxref("HTMLInputElement")}}
- {{domxref("HTMLKeygenElement")}}
- {{domxref("HTMLLabelElement")}}
- {{domxref("HTMLLegendElement")}}
- {{domxref("HTMLLIElement")}}
- {{domxref("HTMLLinkElement")}}
- {{domxref("HTMLMapElement")}}
- {{domxref("HTMLMediaElement")}}
- {{domxref("HTMLMenuElement")}}
- {{domxref("HTMLMetaElement")}}
- {{domxref("HTMLMeterElement")}}
- {{domxref("HTMLModElement")}}
- {{domxref("HTMLObjectElement")}}
- {{domxref("HTMLOListElement")}}
- {{domxref("HTMLOptGroupElement")}}
- {{domxref("HTMLOptionElement")}}
- {{domxref("HTMLOutputElement")}}
- {{domxref("HTMLParagraphElement")}}
- {{domxref("HTMLParamElement")}}
- {{domxref("HTMLPreElement")}}
- {{domxref("HTMLProgressElement")}}
- {{domxref("HTMLQuoteElement")}}
- {{domxref("HTMLScriptElement")}}
- {{domxref("HTMLSelectElement")}}
- {{domxref("HTMLSourceElement")}}
- {{domxref("HTMLSpanElement")}}
- {{domxref("HTMLStyleElement")}}
- {{domxref("HTMLTableElement")}}
- {{domxref("HTMLTableCaptionElement")}}
- {{domxref("HTMLTableCellElement")}}
- {{domxref("HTMLTableDataCellElement")}}
- {{domxref("HTMLTableHeaderCellElement")}}
- {{domxref("HTMLTableColElement")}}
- {{domxref("HTMLTableRowElement")}}
- {{domxref("HTMLTableSectionElement")}}
- {{domxref("HTMLTextAreaElement")}}
- {{domxref("HTMLTimeElement")}}
- {{domxref("HTMLTitleElement")}}
- {{domxref("HTMLTrackElement")}}
- {{domxref("HTMLUListElement")}}
- {{domxref("HTMLUnknownElement")}}
- {{domxref("HTMLVideoElement")}}
-
-
-
-其他介面
-
-
-
- {{domxref("CanvasRenderingContext2D")}}
- {{domxref("CanvasGradient")}}
- {{domxref("CanvasPattern")}}
- {{domxref("TextMetrics")}}
- {{domxref("ImageData")}}
- {{domxref("CanvasPixelArray")}}
- {{domxref("NotifyAudioAvailableEvent")}}
- {{domxref("HTMLAllCollection")}}
- {{domxref("HTMLFormControlsCollection")}}
- {{domxref("HTMLOptionsCollection")}}
- {{domxref("HTMLPropertiesCollection")}}
- {{domxref("DOMStringMap")}}
- {{domxref("RadioNodeList")}}
- {{domxref("MediaError")}}
-
-
-
-棄用的 HTML 介面
-
-
-
- {{domxref("HTMLBaseFontElement")}}
- {{domxref("HTMLIsIndexElement")}}
-
-
-
-SVG 介面
-
-SVG 元素介面
-
-
-
- {{domxref("SVGAElement")}}
- {{domxref("SVGAltGlyphElement")}}
- {{domxref("SVGAltGlyphDefElement")}}
- {{domxref("SVGAltGlyphItemElement")}}
- {{domxref("SVGAnimationElement")}}
- {{domxref("SVGAnimateElement")}}
- {{domxref("SVGAnimateColorElement")}}
- {{domxref("SVGAnimateMotionElement")}}
- {{domxref("SVGAnimateTransformElement")}}
- {{domxref("SVGCircleElement")}}
- {{domxref("SVGClipPathElement")}}
- {{domxref("SVGColorProfileElement")}}
- {{domxref("SVGComponentTransferFunctionElement")}}
- {{domxref("SVGCursorElement")}}
- {{domxref("SVGDefsElement")}}
- {{domxref("SVGDescElement")}}
- {{domxref("SVGElement")}}
- {{domxref("SVGEllipseElement")}}
- {{domxref("SVGFEBlendElement")}}
- {{domxref("SVGFEColorMatrixElement")}}
- {{domxref("SVGFEComponentTransferElement")}}
- {{domxref("SVGFECompositeElement")}}
- {{domxref("SVGFEConvolveMatrixElement")}}
- {{domxref("SVGFEDiffuseLightingElement")}}
- {{domxref("SVGFEDisplacementMapElement")}}
- {{domxref("SVGFEDistantLightElement")}}
- {{domxref("SVGFEFloodElement")}}
- {{domxref("SVGFEGaussianBlurElement")}}
- {{domxref("SVGFEImageElement")}}
- {{domxref("SVGFEMergeElement")}}
- {{domxref("SVGFEMergeNodeElement")}}
- {{domxref("SVGFEMorphologyElement")}}
- {{domxref("SVGFEOffsetElement")}}
- {{domxref("SVGFEPointLightElement")}}
- {{domxref("SVGFESpecularLightingElement")}}
- {{domxref("SVGFESpotLightElement")}}
- {{domxref("SVGFETileElement")}}
- {{domxref("SVGFETurbulenceElement")}}
- {{domxref("SVGFEFuncRElement")}}
- {{domxref("SVGFEFuncGElement")}}
- {{domxref("SVGFEFuncBElement")}}
- {{domxref("SVGFEFuncAElement")}}
- {{domxref("SVGFilterElement")}}
- {{domxref("SVGFilterPrimitiveStandardAttributes")}}
- {{domxref("SVGFontElement")}}
- {{domxref("SVGFontFaceElement")}}
- {{domxref("SVGFontFaceFormatElement")}}
- {{domxref("SVGFontFaceNameElement")}}
- {{domxref("SVGFontFaceSrcElement")}}
- {{domxref("SVGFontFaceUriElement")}}
- {{domxref("SVGForeignObjectElement")}}
- {{domxref("SVGGElement")}}
- {{domxref("SVGGlyphElement")}}
- {{domxref("SVGGlyphRefElement")}}
- {{domxref("SVGGradientElement")}}
- {{domxref("SVGHKernElement")}}
- {{domxref("SVGImageElement")}}
- {{domxref("SVGLinearGradientElement")}}
- {{domxref("SVGLineElement")}}
- {{domxref("SVGMarkerElement")}}
- {{domxref("SVGMaskElement")}}
- {{domxref("SVGMetadataElement")}}
- {{domxref("SVGMissingGlyphElement")}}
- {{domxref("SVGMPathElement")}}
- {{domxref("SVGPathElement")}}
- {{domxref("SVGPatternElement")}}
- {{domxref("SVGPolylineElement")}}
- {{domxref("SVGPolygonElement")}}
- {{domxref("SVGRadialGradientElement")}}
- {{domxref("SVGRectElement")}}
- {{domxref("SVGScriptElement")}}
- {{domxref("SVGSetElement")}}
- {{domxref("SVGStopElement")}}
- {{domxref("SVGStyleElement")}}
- {{domxref("SVGSVGElement")}}
- {{domxref("SVGSwitchElement")}}
- {{domxref("SVGSymbolElement")}}
- {{domxref("SVGTextElement")}}
- {{domxref("SVGTextPathElement")}}
- {{domxref("SVGTitleElement")}}
- {{domxref("SVGTRefElement")}}
- {{domxref("SVGTSpanElement")}}
- {{domxref("SVGUseElement")}}
- {{domxref("SVGViewElement")}}
- {{domxref("SVGVKernElement")}}
-
-
-
-SVG 資料型別介面
-
-這裡是資料型態的 DOM API,在 SVG 特性和性質的定義中被使用。
-
-
-
從 {{Gecko("5.0")}} 開始,下列 SVG 相關的 DOM 介面物件的表示清單,現在可以被索引且可以像陣列般被取用;此外,他們也有 length 屬性來標示其清單中的項目個數:{{domxref("SVGLengthList")}}、{{domxref("SVGNumberList")}}、{{domxref("SVGPathSegList")}},和 {{domxref("SVGPointList")}}。
-
-
-靜態類型
-
-
-
- {{domxref("SVGAngle")}}
- {{domxref("SVGColor")}}
- {{domxref("SVGICCColor")}}
- {{domxref("SVGElementInstance")}}
- {{domxref("SVGElementInstanceList")}}
- {{domxref("SVGLength")}}
- {{domxref("SVGLengthList")}}
- {{domxref("SVGMatrix")}}
- {{domxref("SVGNumber")}}
- {{domxref("SVGNumberList")}}
- {{domxref("SVGPaint")}}
- {{domxref("SVGPoint")}}
- {{domxref("SVGPointList")}}
- {{domxref("SVGPreserveAspectRatio")}}
- {{domxref("SVGRect")}}
- {{domxref("SVGStringList")}}
- {{domxref("SVGTransform")}}
- {{domxref("SVGTransformList")}}
-
-
-
-動畫類型
-
-
-
- {{domxref("SVGAnimatedAngle")}}
- {{domxref("SVGAnimatedBoolean")}}
- {{domxref("SVGAnimatedEnumeration")}}
- {{domxref("SVGAnimatedInteger")}}
- {{domxref("SVGAnimatedLength")}}
- {{domxref("SVGAnimatedLengthList")}}
- {{domxref("SVGAnimatedNumber")}}
- {{domxref("SVGAnimatedNumberList")}}
- {{domxref("SVGAnimatedPreserveAspectRatio")}}
- {{domxref("SVGAnimatedRect")}}
- {{domxref("SVGAnimatedString")}}
- {{domxref("SVGAnimatedTransformList")}}
-
-
-
-SMIL 相關介面
-
-
-
- {{domxref("ElementTimeControl")}}
- {{domxref("TimeEvent")}}
-
-
-
-其他的 SVG 介面
-
-
-
- {{domxref("SVGAnimatedPathData")}}
- {{domxref("SVGAnimatedPoints")}}
- {{domxref("SVGColorProfileRule")}}
- {{domxref("SVGCSSRule")}}
- {{domxref("SVGExternalResourcesRequired")}}
- {{domxref("SVGFitToViewBox")}}
- {{domxref("SVGLangSpace")}}
- {{domxref("SVGLocatable")}}
- {{domxref("SVGRenderingIntent")}}
- {{domxref("SVGStylable")}}
- {{domxref("SVGTests")}}
- {{domxref("SVGTextContentElement")}}
- {{domxref("SVGTextPositioningElement")}}
- {{domxref("SVGTransformable")}}
- {{domxref("SVGUnitTypes")}}
- {{domxref("SVGURIReference")}}
- {{domxref("SVGViewSpec")}}
- {{domxref("SVGZoomAndPan")}}
-
-
-
-相關連結
-
-
+{{DefaultAPISidebar("DOM")}}
+
+**文件物件模型(_Document Object Model, DOM_)**是 HTML、XML 和 SVG 文件的程式介面。它提供了一個文件(樹)的結構化表示法,並定義讓程式可以存取並改變文件架構、風格和內容的方法。DOM 提供了文件以擁有屬性與函式的節點與物件組成的結構化表示。節點也可以附加事件處理程序,一旦觸發事件就會執行處理程序。 本質上,它將網頁與腳本或程式語言連結在一起。
+
+雖然常常使用 JavaScript 來存取 DOM,但它本身並不是 JavaScript 語言的一部分,而且它也可以被其他語言存取(雖然不太常見就是了)。
+
+這裡有一篇 DOM 的[介紹](/zh-TW/docs/DOM/DOM_Reference/Introduction)可供查閱。
+
+## DOM 介面
+
+- {{domxref("Attr")}}
+- {{domxref("CharacterData")}}
+- {{domxref("ChildNode")}} {{experimental_inline}}
+- {{domxref("Comment")}}
+- {{domxref("CustomEvent")}}
+- {{domxref("Document")}}
+- {{domxref("DocumentFragment")}}
+- {{domxref("DocumentType")}}
+- {{domxref("DOMError")}}
+- {{domxref("DOMException")}}
+- {{domxref("DOMImplementation")}}
+- {{domxref("DOMString")}}
+- {{domxref("DOMTimeStamp")}}
+- {{domxref("DOMSettableTokenList")}}
+- {{domxref("DOMStringList")}}
+- {{domxref("DOMTokenList")}}
+- {{domxref("Element")}}
+- {{domxref("Event")}}
+- {{domxref("EventTarget")}}
+- {{domxref("HTMLCollection")}}
+- {{domxref("MutationObserver")}}
+- {{domxref("MutationRecord")}}
+- {{domxref("Node")}}
+- {{domxref("NodeFilter")}}
+- {{domxref("NodeIterator")}}
+- {{domxref("NodeList")}}
+- {{domxref("ParentNode")}} {{experimental_inline}}
+- {{domxref("ProcessingInstruction")}}
+- {{domxref("Range")}}
+- {{domxref("Text")}}
+- {{domxref("TreeWalker")}}
+- {{domxref("URL")}}
+- {{domxref("Window")}}
+- {{domxref("Worker")}}
+- {{domxref("XMLDocument")}} {{experimental_inline}}
+
+## 棄用的 DOM 介面
+
+文件物件模型正被大量的簡化。為了達成這個目的,下這些介面是在 DOM level 3 或更早的規範中就被刪掉了。由於不清楚是否會被再度納入,請姑且當他們已經被遺棄,並避免使用:
+
+- {{domxref("CDATASection")}}
+- {{domxref("DOMConfiguration")}}
+- {{domxref("DOMErrorHandler")}}
+- {{domxref("DOMImplementationList")}}
+- {{domxref("DOMImplementationRegistry")}}
+- {{domxref("DOMImplementationSource")}}
+- {{domxref("DOMLocator")}}
+- {{domxref("DOMObject")}}
+- {{domxref("DOMUserData")}}
+- {{domxref("Entity")}}
+- {{domxref("EntityReference")}}
+- {{domxref("NamedNodeMap")}}
+- {{domxref("NameList")}}
+- {{domxref("Notation")}}
+- {{domxref("TypeInfo")}}
+- {{domxref("UserDataHandler")}}
+-
+
+## HTML 介面
+
+一份包含 html 的文件會透過 {{domxref("HTMLDocument")}} 介面來描述。注意 HTML 規範也擴展了 {{domxref("Document")}} 介面。
+
+`HTMLDocument` 物件也提供了瀏覽器功能的存取:分頁、透過 {{domxref("Window")}} 介面描繪頁面的視窗、與其相關的 {{domxref("window.style", "樣式")}} (通常是 CSS )、與本文關聯的瀏覽器 {{domxref("window.history", "歷史")}}、以及一個文件內的 {{domxref("Selection", "選擇器")}}。
+
+### HTML 元素介面
+
+- {{domxref("HTMLAnchorElement")}}
+- {{domxref("HTMLAppletElement")}}
+- {{domxref("HTMLAreaElement")}}
+- {{domxref("HTMLAudioElement")}}
+- {{domxref("HTMLBaseElement")}}
+- {{domxref("HTMLBodyElement")}}
+- {{domxref("HTMLBRElement")}}
+- {{domxref("HTMLButtonElement")}}
+- {{domxref("HTMLCanvasElement")}}
+- {{domxref("HTMLDataElement")}}
+- {{domxref("HTMLDataListElement")}}
+- {{domxref("HTMLDialogElement")}}
+- {{domxref("HTMLDirectoryElement")}}
+- {{domxref("HTMLDivElement")}}
+- {{domxref("HTMLDListElement")}}
+- {{domxref("HTMLElement")}}
+- {{domxref("HTMLEmbedElement")}}
+- {{domxref("HTMLFieldSetElement")}}
+- {{domxref("HTMLFontElement")}}
+- {{domxref("HTMLFormElement")}}
+- {{domxref("HTMLFrameElement")}}
+- {{domxref("HTMLFrameSetElement")}}
+- {{domxref("HTMLHeadElement")}}
+- {{domxref("HTMLHeadingElement")}}
+- {{domxref("HTMLHtmlElement")}}
+- {{domxref("HTMLHRElement")}}
+- {{domxref("HTMLIFrameElement")}}
+- {{domxref("HTMLImageElement")}}
+- {{domxref("HTMLInputElement")}}
+- {{domxref("HTMLKeygenElement")}}
+- {{domxref("HTMLLabelElement")}}
+- {{domxref("HTMLLegendElement")}}
+- {{domxref("HTMLLIElement")}}
+- {{domxref("HTMLLinkElement")}}
+- {{domxref("HTMLMapElement")}}
+- {{domxref("HTMLMediaElement")}}
+- {{domxref("HTMLMenuElement")}}
+- {{domxref("HTMLMetaElement")}}
+- {{domxref("HTMLMeterElement")}}
+- {{domxref("HTMLModElement")}}
+- {{domxref("HTMLObjectElement")}}
+- {{domxref("HTMLOListElement")}}
+- {{domxref("HTMLOptGroupElement")}}
+- {{domxref("HTMLOptionElement")}}
+- {{domxref("HTMLOutputElement")}}
+- {{domxref("HTMLParagraphElement")}}
+- {{domxref("HTMLParamElement")}}
+- {{domxref("HTMLPreElement")}}
+- {{domxref("HTMLProgressElement")}}
+- {{domxref("HTMLQuoteElement")}}
+- {{domxref("HTMLScriptElement")}}
+- {{domxref("HTMLSelectElement")}}
+- {{domxref("HTMLSourceElement")}}
+- {{domxref("HTMLSpanElement")}}
+- {{domxref("HTMLStyleElement")}}
+- {{domxref("HTMLTableElement")}}
+- {{domxref("HTMLTableCaptionElement")}}
+- {{domxref("HTMLTableCellElement")}}
+- {{domxref("HTMLTableDataCellElement")}}
+- {{domxref("HTMLTableHeaderCellElement")}}
+- {{domxref("HTMLTableColElement")}}
+- {{domxref("HTMLTableRowElement")}}
+- {{domxref("HTMLTableSectionElement")}}
+- {{domxref("HTMLTextAreaElement")}}
+- {{domxref("HTMLTimeElement")}}
+- {{domxref("HTMLTitleElement")}}
+- {{domxref("HTMLTrackElement")}}
+- {{domxref("HTMLUListElement")}}
+- {{domxref("HTMLUnknownElement")}}
+- {{domxref("HTMLVideoElement")}}
+
+### 其他介面
+
+- {{domxref("CanvasRenderingContext2D")}}
+- {{domxref("CanvasGradient")}}
+- {{domxref("CanvasPattern")}}
+- {{domxref("TextMetrics")}}
+- {{domxref("ImageData")}}
+- {{domxref("CanvasPixelArray")}}
+- {{domxref("NotifyAudioAvailableEvent")}}
+- {{domxref("HTMLAllCollection")}}
+- {{domxref("HTMLFormControlsCollection")}}
+- {{domxref("HTMLOptionsCollection")}}
+- {{domxref("HTMLPropertiesCollection")}}
+- {{domxref("DOMStringMap")}}
+- {{domxref("RadioNodeList")}}
+- {{domxref("MediaError")}}
+
+### 棄用的 HTML 介面
+
+- {{domxref("HTMLBaseFontElement")}}
+- {{domxref("HTMLIsIndexElement")}}
+
+## SVG 介面
+
+### SVG 元素介面
+
+- {{domxref("SVGAElement")}}
+- {{domxref("SVGAltGlyphElement")}}
+- {{domxref("SVGAltGlyphDefElement")}}
+- {{domxref("SVGAltGlyphItemElement")}}
+- {{domxref("SVGAnimationElement")}}
+- {{domxref("SVGAnimateElement")}}
+- {{domxref("SVGAnimateColorElement")}}
+- {{domxref("SVGAnimateMotionElement")}}
+- {{domxref("SVGAnimateTransformElement")}}
+- {{domxref("SVGCircleElement")}}
+- {{domxref("SVGClipPathElement")}}
+- {{domxref("SVGColorProfileElement")}}
+- {{domxref("SVGComponentTransferFunctionElement")}}
+- {{domxref("SVGCursorElement")}}
+- {{domxref("SVGDefsElement")}}
+- {{domxref("SVGDescElement")}}
+- {{domxref("SVGElement")}}
+- {{domxref("SVGEllipseElement")}}
+- {{domxref("SVGFEBlendElement")}}
+- {{domxref("SVGFEColorMatrixElement")}}
+- {{domxref("SVGFEComponentTransferElement")}}
+- {{domxref("SVGFECompositeElement")}}
+- {{domxref("SVGFEConvolveMatrixElement")}}
+- {{domxref("SVGFEDiffuseLightingElement")}}
+- {{domxref("SVGFEDisplacementMapElement")}}
+- {{domxref("SVGFEDistantLightElement")}}
+- {{domxref("SVGFEFloodElement")}}
+- {{domxref("SVGFEGaussianBlurElement")}}
+- {{domxref("SVGFEImageElement")}}
+- {{domxref("SVGFEMergeElement")}}
+- {{domxref("SVGFEMergeNodeElement")}}
+- {{domxref("SVGFEMorphologyElement")}}
+- {{domxref("SVGFEOffsetElement")}}
+- {{domxref("SVGFEPointLightElement")}}
+- {{domxref("SVGFESpecularLightingElement")}}
+- {{domxref("SVGFESpotLightElement")}}
+- {{domxref("SVGFETileElement")}}
+- {{domxref("SVGFETurbulenceElement")}}
+- {{domxref("SVGFEFuncRElement")}}
+- {{domxref("SVGFEFuncGElement")}}
+- {{domxref("SVGFEFuncBElement")}}
+- {{domxref("SVGFEFuncAElement")}}
+- {{domxref("SVGFilterElement")}}
+- {{domxref("SVGFilterPrimitiveStandardAttributes")}}
+- {{domxref("SVGFontElement")}}
+- {{domxref("SVGFontFaceElement")}}
+- {{domxref("SVGFontFaceFormatElement")}}
+- {{domxref("SVGFontFaceNameElement")}}
+- {{domxref("SVGFontFaceSrcElement")}}
+- {{domxref("SVGFontFaceUriElement")}}
+- {{domxref("SVGForeignObjectElement")}}
+- {{domxref("SVGGElement")}}
+- {{domxref("SVGGlyphElement")}}
+- {{domxref("SVGGlyphRefElement")}}
+- {{domxref("SVGGradientElement")}}
+- {{domxref("SVGHKernElement")}}
+- {{domxref("SVGImageElement")}}
+- {{domxref("SVGLinearGradientElement")}}
+- {{domxref("SVGLineElement")}}
+- {{domxref("SVGMarkerElement")}}
+- {{domxref("SVGMaskElement")}}
+- {{domxref("SVGMetadataElement")}}
+- {{domxref("SVGMissingGlyphElement")}}
+- {{domxref("SVGMPathElement")}}
+- {{domxref("SVGPathElement")}}
+- {{domxref("SVGPatternElement")}}
+- {{domxref("SVGPolylineElement")}}
+- {{domxref("SVGPolygonElement")}}
+- {{domxref("SVGRadialGradientElement")}}
+- {{domxref("SVGRectElement")}}
+- {{domxref("SVGScriptElement")}}
+- {{domxref("SVGSetElement")}}
+- {{domxref("SVGStopElement")}}
+- {{domxref("SVGStyleElement")}}
+- {{domxref("SVGSVGElement")}}
+- {{domxref("SVGSwitchElement")}}
+- {{domxref("SVGSymbolElement")}}
+- {{domxref("SVGTextElement")}}
+- {{domxref("SVGTextPathElement")}}
+- {{domxref("SVGTitleElement")}}
+- {{domxref("SVGTRefElement")}}
+- {{domxref("SVGTSpanElement")}}
+- {{domxref("SVGUseElement")}}
+- {{domxref("SVGViewElement")}}
+- {{domxref("SVGVKernElement")}}
+
+### SVG 資料型別介面
+
+這裡是資料型態的 DOM API,在 SVG 特性和性質的定義中被使用。
+
+> **備註:** 從 {{Gecko("5.0")}} 開始,下列 SVG 相關的 DOM 介面物件的表示清單,現在可以被索引且可以像陣列般被取用;此外,他們也有 length 屬性來標示其清單中的項目個數:{{domxref("SVGLengthList")}}、{{domxref("SVGNumberList")}}、{{domxref("SVGPathSegList")}},和 {{domxref("SVGPointList")}}。
+
+#### 靜態類型
+
+- {{domxref("SVGAngle")}}
+- {{domxref("SVGColor")}}
+- {{domxref("SVGICCColor")}}
+- {{domxref("SVGElementInstance")}}
+- {{domxref("SVGElementInstanceList")}}
+- {{domxref("SVGLength")}}
+- {{domxref("SVGLengthList")}}
+- {{domxref("SVGMatrix")}}
+- {{domxref("SVGNumber")}}
+- {{domxref("SVGNumberList")}}
+- {{domxref("SVGPaint")}}
+- {{domxref("SVGPoint")}}
+- {{domxref("SVGPointList")}}
+- {{domxref("SVGPreserveAspectRatio")}}
+- {{domxref("SVGRect")}}
+- {{domxref("SVGStringList")}}
+- {{domxref("SVGTransform")}}
+- {{domxref("SVGTransformList")}}
+
+#### 動畫類型
+
+- {{domxref("SVGAnimatedAngle")}}
+- {{domxref("SVGAnimatedBoolean")}}
+- {{domxref("SVGAnimatedEnumeration")}}
+- {{domxref("SVGAnimatedInteger")}}
+- {{domxref("SVGAnimatedLength")}}
+- {{domxref("SVGAnimatedLengthList")}}
+- {{domxref("SVGAnimatedNumber")}}
+- {{domxref("SVGAnimatedNumberList")}}
+- {{domxref("SVGAnimatedPreserveAspectRatio")}}
+- {{domxref("SVGAnimatedRect")}}
+- {{domxref("SVGAnimatedString")}}
+- {{domxref("SVGAnimatedTransformList")}}
+
+### SMIL 相關介面
+
+- {{domxref("ElementTimeControl")}}
+- {{domxref("TimeEvent")}}
+
+### 其他的 SVG 介面
+
+- {{domxref("SVGAnimatedPathData")}}
+- {{domxref("SVGAnimatedPoints")}}
+- {{domxref("SVGColorProfileRule")}}
+- {{domxref("SVGCSSRule")}}
+- {{domxref("SVGExternalResourcesRequired")}}
+- {{domxref("SVGFitToViewBox")}}
+- {{domxref("SVGLangSpace")}}
+- {{domxref("SVGLocatable")}}
+- {{domxref("SVGRenderingIntent")}}
+- {{domxref("SVGStylable")}}
+- {{domxref("SVGTests")}}
+- {{domxref("SVGTextContentElement")}}
+- {{domxref("SVGTextPositioningElement")}}
+- {{domxref("SVGTransformable")}}
+- {{domxref("SVGUnitTypes")}}
+- {{domxref("SVGURIReference")}}
+- {{domxref("SVGViewSpec")}}
+- {{domxref("SVGZoomAndPan")}}
+
+## 相關連結
+
+- [DOM 範例](/zh-TW/docs/DOM/DOM_Reference/Examples)
diff --git a/files/zh-tw/web/api/document_object_model/whitespace/index.md b/files/zh-tw/web/api/document_object_model/whitespace/index.md
index bb04573e065533..dea63bbb19a5c5 100644
--- a/files/zh-tw/web/api/document_object_model/whitespace/index.md
+++ b/files/zh-tw/web/api/document_object_model/whitespace/index.md
@@ -6,33 +6,40 @@ tags:
- 所有類別
translation_of: Web/API/Document_Object_Model/Whitespace
---
-問題說明
-DOM 裡的空白字元會讓處理節點結構時增加不少麻煩。Mozilla 相關軟體中,原始文件裡所有空白字元都會在 DOM 中出現(不包括標籤內含的空白字元)。這樣的處理方式有其必要,一方面編輯器中可逕行排列文字、二方面 CSS 裡的 white-space: pre
也才能發揮作用。 如此一來就表示:
-
- 有些空白字元會自成一個文字節點。
- 有些空白字元會與其他字串合成一個文字節點。
-
-換句話說,下面這段程式碼的 DOM 節點結構就如附圖一般,其中「\n」代表換行字元:
-<!-- My document -->
-<html>
-<head>
- <title>My Document</title>
-</head>
-<body>
- <h1>Header</h1>
- <p>
+#### 問題說明
+
+[DOM](zh_tw/DOM) 裡的空白字元會讓處理節點結構時增加不少麻煩。Mozilla 相關軟體中,原始文件裡所有空白字元都會在 DOM 中出現(不包括標籤內含的空白字元)。這樣的處理方式有其必要,一方面編輯器中可逕行排列文字、二方面 [CSS](zh_tw/CSS) 裡的 `white-space: pre` 也才能發揮作用。 如此一來就表示:
+
+- 有些空白字元會自成一個文字節點。
+- 有些空白字元會與其他字串合成一個文字節點。
+
+換句話說,下面這段程式碼的 DOM 節點結構就如附圖一般,其中「\n」代表換行字元:
+
+```html
+
+
+
+ My Document
+
+
+ Header
+
Paragraph
- </p>
-</body>
-</html>
-
+
+
+
+```
+
+![](https://mdn.mozillademos.org/files/854/whitespace_tree.png)
+
+這麼一來,要使用 DOM 遊走於節點結構間又不想要無用的空白字元時,會有點困難。
-
+#### 助你一臂之力
-這麼一來,要使用 DOM 遊走於節點結構間又不想要無用的空白字元時,會有點困難。
-助你一臂之力
-以下的 JavaScript 程式碼定義了許多函式,讓你處理 DOM 中的空白字元時能輕鬆點:
-/**
+以下的 JavaScript 程式碼定義了許多函式,讓你處理 DOM 中的空白字元時能輕鬆點:
+
+```js
+/**
* 以下所謂的「空白字元」代表:
* "\t" TAB \u0009 (移位字元)
* "\n" LF \u000A (換行字元)
@@ -67,7 +74,7 @@ function is_all_ws( nod )
function is_ignorable( nod )
{
return ( nod.nodeType == 8) || // 註解節點
- ( (nod.nodeType == 3) && is_all_ws(nod) ); // 僅含空白字元的文字節點
+ ( (nod.nodeType == 3) && is_all_ws(nod) ); // 僅含空白字元的文字節點
}
/**
@@ -159,10 +166,14 @@ function data_of( txt )
data = data.substring(0, data.length - 1);
return data;
}
-
-範例
-以下示範上述函式的應用方法,在節點結構中依序檢查、找出內容為「"This is the third paragraph"
」的節點,並修改其 class 屬性及文字內容。
-var cur = first_child(document.getElementById("test"));
+```
+
+#### 範例
+
+以下示範上述函式的應用方法,在節點結構中依序檢查、找出內容為「`"This is the third paragraph"`」的節點,並修改其 class 屬性及文字內容。
+
+```js
+var cur = first_child(document.getElementById("test"));
while (cur)
{
if (data_of(cur.firstChild) == "This is the third paragraph.")
@@ -172,4 +183,4 @@ while (cur)
}
cur = node_after(cur);
}
-
+```
diff --git a/files/zh-tw/web/api/documentfragment/index.md b/files/zh-tw/web/api/documentfragment/index.md
index a007233e7dfa84..826dfdfa7e4ee0 100644
--- a/files/zh-tw/web/api/documentfragment/index.md
+++ b/files/zh-tw/web/api/documentfragment/index.md
@@ -3,68 +3,57 @@ title: DocumentFragment
slug: Web/API/DocumentFragment
translation_of: Web/API/DocumentFragment
---
-{{ ApiRef("DOM") }}
+{{ ApiRef("DOM") }}
-DocumentFragment
介面表示了一個沒有父節點的最小化文件物件。DocumentFragment
被當作一種輕量化的 {{domxref("Document")}},用如同標準文件一般的方式保存片段的文件結構(由節點組成)。關鍵的區別在於文件片段不是真實的 DOM 結構,文件片段的變動並不會影響目前的網頁文件,也不會導致回流({{Glossary("reflow")}})或引起任何影響效能的情況發生。
+**`DocumentFragment`** 介面表示了一個沒有父節點的最小化文件物件。`DocumentFragment` 被當作一種輕量化的 {{domxref("Document")}},用如同標準文件一般的方式保存片段的文件結構(由節點組成)。關鍵的區別在於文件片段不是真實的 DOM 結構,文件片段的變動並不會影響目前的網頁文件,也不會導致回流({{Glossary("reflow")}})或引起任何影響效能的情況發生。
-一般的用法是建立一個 DocumentFragment
物件,在此物件中組織一個 DOM 的子樹。再使用 {{domxref("Node")}} 介面定義的方法,如 {{domxref("Node.appendChild", "appendChild()")}} 或 {{domxref("Node.insertBefore", "insertBefore()")}} 將這個文件片段加入或插入目前頁面的 DOM 當中。執行這個將文件片段中的節點置入 DOM 的動作之後,會留下一個空的 DocumentFragment
物件(只會插入物件中的節點,DocumentFragment
物件本身不會被插入)。由於文件片段中的所有節點是一次性的被插入目前頁面文件當中,故回流及頁面渲染只會被觸發一次,所以可用插入 DocumentFragment
物件的方式取代傳統分別插入多個節點至 DOM(將節點一個一個分次進行插入)的操作方式。
+一般的用法是建立一個 `DocumentFragment` 物件,在此物件中組織一個 DOM 的子樹。再使用 {{domxref("Node")}} 介面定義的方法,如 {{domxref("Node.appendChild", "appendChild()")}} 或 {{domxref("Node.insertBefore", "insertBefore()")}} 將這個文件片段加入或插入目前頁面的 DOM 當中。執行這個將文件片段中的節點置入 DOM 的動作之後,會留下一個空的 `DocumentFragment` 物件(只會插入物件中的節點,`DocumentFragment` 物件本身不會被插入)。由於文件片段中的所有節點是一次性的被插入目前頁面文件當中,故回流及頁面渲染只會被觸發一次,所以可用插入 `DocumentFragment` 物件的方式取代傳統分別插入多個節點至 DOM(將節點一個一個分次進行插入)的操作方式。
-此介面也適合與 Web components 搭配使用:{{HTMLElement("template")}} 元素在其 {{domxref("HTMLTemplateElement.content")}} 屬性中便包含了一個 DocumentFragment
物件。
+此介面也適合與 Web components 搭配使用:{{HTMLElement("template")}} 元素在其 {{domxref("HTMLTemplateElement.content")}} 屬性中便包含了一個 `DocumentFragment` 物件。
-可使用 {{domxref("document.createDocumentFragment()")}} 方法或 DocumentFragment
的建構式來建立一個空的 DocumentFragment
物件。
+可使用 {{domxref("document.createDocumentFragment()")}} 方法或 `DocumentFragment` 的建構式來建立一個空的 `DocumentFragment` 物件。
-屬性
+## 屬性
-This interface has no specific properties, but inherits those of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface.
+_This interface has no specific properties, but inherits those of its parent,_ _{{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface._
-
- {{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
- Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} that are children of the DocumentFragment
object.
- {{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
- Returns the {{domxref("Element")}} that is the first child of the DocumentFragment
object, or null
if there is none.
- {{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
- Returns the {{domxref("Element")}} that is the last child of the DocumentFragment
object, or null
if there is none.
- {{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
- Returns an unsigned long
giving the amount of children that the DocumentFragment
has.
-
+- {{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+ - : Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} that are children of the `DocumentFragment` object.
+- {{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
+ - : Returns the {{domxref("Element")}} that is the first child of the `DocumentFragment` object, or `null` if there is none.
+- {{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
+ - : Returns the {{domxref("Element")}} that is the last child of the `DocumentFragment` object, or `null` if there is none.
+- {{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
+ - : Returns an `unsigned long` giving the amount of children that the `DocumentFragment` has.
-建構式
+## 建構式
-
- {{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
- Returns an empty DocumentFragment
object.
-
+- {{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+ - : Returns an empty `DocumentFragment` object.
-方法
+## 方法
-This interface inherits the methods of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface .
+_This interface inherits the methods of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface*.*_
-
- {{domxref("DocumentFragment.find()")}} {{experimental_inline}}
- Returns the first matching {{domxref("Element")}} in the tree of the DocumentFragment
.
- {{domxref("DocumentFragment.findAll()")}} {{experimental_inline}}
- Returns a {{domxref("NodeList")}} of matching {{domxref("Element")}} in the tree of the DocumentFragment
.
- {{domxref("DocumentFragment.querySelector()")}}
- Returns the first {{domxref("Element")}} node within the DocumentFragment
, in document order, that matches the specified selectors.
- {{domxref("DocumentFragment.querySelectorAll()")}}
- Returns a {{domxref("NodeList")}} of all the {{domxref("Element")}} nodes within the DocumentFragment
that match the specified selectors.
-
+- {{domxref("DocumentFragment.find()")}} {{experimental_inline}}
+ - : Returns the first matching {{domxref("Element")}} in the tree of the `DocumentFragment`.
+- {{domxref("DocumentFragment.findAll()")}} {{experimental_inline}}
+ - : Returns a {{domxref("NodeList")}} of matching {{domxref("Element")}} in the tree of the `DocumentFragment`.
+- {{domxref("DocumentFragment.querySelector()")}}
+ - : Returns the first {{domxref("Element")}} node within the `DocumentFragment`, in document order, that matches the specified selectors.
+- {{domxref("DocumentFragment.querySelectorAll()")}}
+ - : Returns a {{domxref("NodeList")}} of all the {{domxref("Element")}} nodes within the `DocumentFragment` that match the specified selectors.
+- {{domxref("DocumentFragment.getElementById()")}}
+ - : Returns the first {{domxref("Element")}} node within the `DocumentFragment`, in document order, that matches the specified ID.
-
- {{domxref("DocumentFragment.getElementById()")}}
- Returns the first {{domxref("Element")}} node within the DocumentFragment
, in document order, that matches the specified ID.
-
-
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.DocumentFragment")}}
-參見
+## 參見
-
+- [The DOM interfaces index.](/docs/DOM/DOM_Reference)
diff --git a/files/zh-tw/web/api/element/classlist/index.md b/files/zh-tw/web/api/element/classlist/index.md
index b7f5833b7d6ec2..08fce9fd0d558a 100644
--- a/files/zh-tw/web/api/element/classlist/index.md
+++ b/files/zh-tw/web/api/element/classlist/index.md
@@ -3,38 +3,38 @@ title: Element.classList
slug: Web/API/Element/classList
translation_of: Web/API/Element/classList
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-Element.classList
唯讀屬性代表了該元素所擁有之類別屬性(Class
{{Glossary("Attribute")}})的即時更新集-{{domxref("DOMTokenList")}}。
+**`Element.classList`** 唯讀屬性代表了該元素所擁有之類別屬性(`Class` {{Glossary("Attribute")}})的即時更新集-{{domxref("DOMTokenList")}}。
-使用 classList
屬性是取得元素 Class
的一種便利方式,也可以透過 {{domxref("element.className")}} 來得到以空格分隔之 Class
清單字串。
+使用 `classList` 屬性是取得元素 `Class` 的一種便利方式,也可以透過 {{domxref("element.className")}} 來得到以空格分隔之 `Class` 清單字串。
-語法
+## 語法
-var elementClasses = elementNodeReference.classList;
-
+```plain
+var elementClasses = elementNodeReference.classList;
+```
-elementClasses is a {{domxref("DOMTokenList")}} representing the class attribute of elementNodeReference . If the class attribute was not set or is empty elementClasses.length returns 0. element.classList
itself is read-only, although you can modify it using the add()
and remove()
methods.
+_elementClasses_ is a {{domxref("DOMTokenList")}} representing the class attribute of _elementNodeReference_. If the class attribute was not set or is empty _elementClasses.length_ returns 0. `element.classList` itself is read-only, although you can modify it using the` add()` and `remove()` methods.
-方法
+## 方法
-
- add( String [, String] )
- Add specified class values. If these classes already exist in attribute of the element, then they are ignored.
- remove( String [,String] )
- Remove specified class values.
- item ( Number )
- Return class value by index in collection.
- toggle ( String [, force] )
- When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
- When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
- contains( String )
- Checks if specified class value exists in class attribute of the element.
-
+- add( String \[, String] )
+ - : Add specified class values. If these classes already exist in attribute of the element, then they are ignored.
+- remove( String \[,String] )
+ - : Remove specified class values.
+- **item** ( Number )
+ - : Return class value by index in collection.
+- **toggle** ( String \[, force] )
+ - : When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
+ When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
+- contains( String )
+ - : Checks if specified class value exists in class attribute of the element.
-範例
+## 範例
-// div is an object reference to a <div> element with class="foo bar"
+```js
+// div is an object reference to a element with class="foo bar"
div.classList.remove("foo");
div.classList.add("anotherclass");
@@ -42,21 +42,21 @@ div.classList.add("anotherclass");
div.classList.toggle("visible");
// add/remove visible, depending on test conditional, i less than 10
-div.classList.toggle("visible", i < 10 );
+div.classList.toggle("visible", i < 10 );
alert(div.classList.contains("foo"));
-div.classList.add("foo","bar"); //add multiple classes
+div.classList.add("foo","bar"); //add multiple classes
+```
-
+> **備註:** Versions of Firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods. See
-JavaScript shim for other implementations
+## JavaScript shim for other implementations
-Note: This shim does not work in Internet Explorer versions less than 8.
+> **備註:** This shim does not work in Internet Explorer versions less than 8.
-/*
+```js
+/*
* classList.js: Cross-browser full element.classList implementation.
* 2014-07-23
*
@@ -93,8 +93,8 @@ var
i = 0
, len = this.length
;
- for (; i < len; i++) {
- if (i in this && this[i] === item) {
+ for (; i < len; i++) {
+ if (i in this && this[i] === item) {
return i;
}
}
@@ -128,7 +128,7 @@ var
, i = 0
, len = classes.length
;
- for (; i < len; i++) {
+ for (; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
@@ -165,7 +165,7 @@ classListProto.add = function () {
updated = true;
}
}
- while (++i < l);
+ while (++i < l);
if (updated) {
this._updateClassName();
@@ -189,7 +189,7 @@ classListProto.remove = function () {
index = checkTokenAndGetIndex(this, token);
}
}
- while (++i < l);
+ while (++i < l);
if (updated) {
this._updateClassName();
@@ -201,9 +201,9 @@ classListProto.toggle = function (token, force) {
var
result = this.contains(token)
, method = result ?
- force !== true && "remove"
+ force !== true && "remove"
:
- force !== false && "add"
+ force !== false && "add"
;
if (method) {
@@ -251,7 +251,7 @@ if (objCtr.defineProperty) {
testElement.classList.add("c1", "c2");
- // Polyfill for IE 10/11 and Firefox <26, where classList.add and
+ // Polyfill for IE 10/11 and Firefox <26, where classList.add and
// classList.remove exist but support only one argument at a time.
if (!testElement.classList.contains("c2")) {
var createMethod = function(method) {
@@ -260,7 +260,7 @@ if (objCtr.defineProperty) {
DOMTokenList.prototype[method] = function(token) {
var i, len = arguments.length;
- for (i = 0; i < len; i++) {
+ for (i = 0; i < len; i++) {
token = arguments[i];
original.call(this, token);
}
@@ -272,13 +272,13 @@ if (objCtr.defineProperty) {
testElement.classList.toggle("c3", false);
- // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
+ // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
// support the second argument.
if (testElement.classList.contains("c3")) {
var _toggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function(token, force) {
- if (1 in arguments && !this.contains(token) === !force) {
+ if (1 in arguments && !this.contains(token) === !force) {
return force;
} else {
return _toggle.call(this, token);
@@ -292,19 +292,18 @@ if (objCtr.defineProperty) {
}
-}
+}
+```
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Element.classList")}}
-參見
+## 參見
-
- {{domxref("element.className")}}
- {{domxref("DOMTokenList")}};
-
+- {{domxref("element.className")}}
+- {{domxref("DOMTokenList")}};
diff --git a/files/zh-tw/web/api/element/index.md b/files/zh-tw/web/api/element/index.md
index 1d815909acaa05..ad954763296757 100644
--- a/files/zh-tw/web/api/element/index.md
+++ b/files/zh-tw/web/api/element/index.md
@@ -11,204 +11,189 @@ tags:
- Élément(2)
translation_of: Web/API/Element
---
-{{ APIRef("DOM") }}
-
-Element
介面表示了一個在 {{domxref("Document")}} 中的物件,其描述了各類型元素的共同屬性與方法,Element
的子介面則定義了不同類型元素的具體行為並增加額外的功能。例如 {{domxref("HTMLElement")}} 為所有 HTML 元素的基礎介面,而 {{domxref("SVGElement")}} 則是定義所有 SVG 元素的介面。
-
-在 Web 領域之外,如 XUL 語言也能藉由 XULElement
介面來繼承 Element
。
-
-{{InheritanceDiagram}}
-
-屬性
-
-Inherits properties from its parent interface, {{domxref("Node")}}, and by extension that interface's parent, {{domxref("EventTarget")}}. It implements the properties of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.
-
-
- {{ domxref("Element.assignedSlot")}} {{experimental_inline}} {{readOnlyInline}}
- Returns the {{domxref("HTMLSlotElement")}} interface associated with the element.
- {{ domxref("Element.attributes") }} {{readOnlyInline}}
- Returns a {{ domxref("NamedNodeMap") }} object containing the assigned attributes of the corresponding HTML element.
- {{ domxref("Element.classList") }} {{readOnlyInline}}
- Returns a {{ domxref("DOMTokenList") }} containing the list of class attributes.
- {{ domxref("Element.className") }}
- Is a {{domxref("DOMString")}} representing the class of the element.
- {{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the inner height of the element.
- {{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the width of the left border of the element.
- {{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the width of the top border of the element.
- {{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the inner width of the element.
- {{domxref("Element.computedName")}} {{readOnlyInline}}
- Returns a {{domxref("DOMString")}} containing the label exposed to accessibility.
- {{domxref("Element.computedRole")}} {{readOnlyInline}}
- Returns a {{domxref("DOMString")}} containing the ARIA role that has been applied to a particular element.
- {{ domxref("Element.id") }}
- Is a {{domxref("DOMString")}} representing the id of the element.
- {{ domxref("Element.innerHTML") }}
- Is a {{domxref("DOMString")}} representing the markup of the element's content.
- {{ domxref("Element.localName") }} {{readOnlyInline}}
- A {{domxref("DOMString")}} representing the local part of the qualified name of the element.
- {{domxref("Element.namespaceURI")}} {{readonlyInline}}
- The namespace URI of the element, or null
if it is no namespace.
-
-
Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml
namespace in both HTML and XML trees.
-
-
- {{ domxref("NonDocumentTypeChildNode.nextElementSibling") }} {{readOnlyInline}}
- Is a {{ domxref("Element") }}, the element immediately following the given one in the tree, or null
if there's no sibling node.
- {{ domxref("Element.outerHTML") }} {{experimental_inline}}
- Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
- {{ domxref("Element.prefix") }} {{readOnlyInline}}
- A {{domxref("DOMString")}} representing the namespace prefix of the element, or null
if no prefix is specified.
- {{ domxref("NonDocumentTypeChildNode.previousElementSibling") }} {{readOnlyInline}}
- Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or null
if there is no sibling element.
- {{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the scroll view height of an element.
- {{ domxref("Element.scrollLeft") }} {{experimental_inline}}
- Is a {{jsxref("Number")}} representing the left scroll offset of the element.
- {{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
- {{ domxref("Element.scrollTop") }} {{experimental_inline}}
- Is a {{jsxref("Number")}} representing the top scroll offset the an element.
- {{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
- {{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
- Returns a {{jsxref("Number")}} representing the scroll view width of the element.
- {{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
- Returns the youngest shadow root that is hosted by the element.
- {{domxref("Element.slot")}} {{experimental_inline}}
- Returns the name of the shadow DOM slot attatched to the element. A slot is a placeholder inside a web component that users can fill with their own markup.
- {{domxref("Element.tabStop")}} {{non-standard_inline}}
- Is a {{jsxref("Boolean")}} indicating if the element can receive input focus via the tab key.
- {{ domxref("Element.tagName") }} {{readOnlyInline}}
- Returns a {{domxref("String")}} with the name of the tag for the given element.
- {{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
- Returns the {{domxref("UndoManager")}} associated with the element.
- {{ domxref("Element.undoScope")}} {{experimental_inline}}
- Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
-
-
-
-
Note: DOM Level 3 defined namespaceURI
, localName
and prefix
on the {{domxref("Node")}} interface. In DOM4 they were moved to Element
.
-
-
This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.
-
-
-事件處理器
-
-
- {{ domxref("Element.ongotpointercapture") }}
- Returns the event handler for the {{event("gotpointercapture")}} event type.
- {{ domxref("Element.onlostpointercapture") }}
- Returns the event handler for the {{event("lostpointercapture")}} event type.
- {{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
- Returns the event handling code for the wheel
event.
-
-
-方法
-
-Inherits methods from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.
-
-
- {{ domxref("EventTarget.addEventListener()") }}
- Registers an event handler to a specific event type on the element.
- {{domxref("Element.attachShadow()")}} {{experimental_inline}}
- Attatches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}}.
- {{domxref("Element.animate()")}} {{experimental_inline}}
- A shortcut method to create and run an animation on an element. Returns the created Animation object instance.
- {{ domxref("Element.closest()")}} {{experimental_inline}}
- Returns the {{domxref("Element")}}, descendant of this element (or this element itself), that is the closest ancestor of the elements selected by the selectors given in parameter.
- {{ domxref("Element.createShadowRoot()")}} {{experimental_inline}} {{deprecated_inline()}}
- Creates a shadow DOM on on the element, turning it into a shadow host. Returns a {{domxref("ShadowRoot")}}.
- {{ domxref("EventTarget.dispatchEvent()") }}
- Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates that at least one handler has not canceled it.
- {{domxref("Element.find()")}}{{experimental_inline}}
- ...
- {{domxref("Element.findAll()")}}{{experimental_inline}}
- ...
- {{domxref("Element.getAnimations()")}} {{experimental_inline}}
- Returns an array of Animation objects currently active on the element.
- {{ domxref("Element.getAttribute()") }}
- Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
- {{ domxref("Element.getAttributeNames()") }}
- TBD
- {{ domxref("Element.getAttributeNS()") }}
- Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
- {{ domxref("Element.getAttributeNode()") }} {{Deprecated_Inline}}
- Retrieves the node representation of the named attribute from the current node and returns it as an {{ domxref("Attr") }}.
- {{ domxref("Element.getAttributeNodeNS()") }} {{Deprecated_Inline}}
- Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{ domxref("Attr") }}.
- {{ domxref("Element.getBoundingClientRect()") }}
- ...
- {{ domxref("Element.getClientRects()") }}
- Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
- {{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
- …
- {{ domxref("Element.getElementsByClassName()") }}
- Returns a live {{ domxref("HTMLCollection") }} that contains all descendants of the current element that possess the list of classes given in the parameter.
- {{ domxref("Element.getElementsByTagName()") }}
- Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
- {{ domxref("Element.getElementsByTagNameNS()") }}
- Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
- {{ domxref("Element.hasAttribute()") }}
- Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
- {{ domxref("Element.hasAttributeNS()") }}
- Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
- {{ domxref("Element.hasAttributes()") }}
- Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
- {{ domxref("Element.insertAdjacentElement") }} {{experimental_inline}}
- Inserts a given element node at a given position relative to the element it is invoked upon.
- {{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
- Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
- {{ domxref("Element.insertAdjacentText") }} {{experimental_inline}}
- Inserts a given text node at a given position relative to the element it is invoked upon.
- {{ domxref("Element.matches()") }}
{{experimental_inline}}
- Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
- {{ domxref("Element.querySelector()") }}
- Returns the first {{ domxref("Node") }} which matches the specified selector string relative to the element.
- {{ domxref("Element.querySelectorAll") }}
- Returns a {{ domxref("NodeList") }} of nodes which match the specified selector string relative to the element.
- {{ domxref("Element.releasePointerCapture")}}
- Releases (stops) pointer capture that was previously set for a specific {{domxref("PointerEvent","pointer event")}}.
- {{domxref("ChildNode.remove()")}} {{experimental_inline}}
- Removes the element from the children list of its parent.
- {{ domxref("Element.removeAttribute()") }}
- Removes the named attribute from the current node.
- {{ domxref("Element.removeAttributeNS()") }}
- Removes the attribute with the specified name and namespace, from the current node.
- {{ domxref("Element.removeAttributeNode()") }} {{Deprecated_Inline}}
- Removes the node representation of the named attribute from the current node.
- {{ domxref("EventTarget.removeEventListener()") }}
- Removes an event listener from the element.
- {{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
- Asynchronously asks the browser to make the element full-screen.
- {{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
- Allows to asynchronously ask for the pointer to be locked on the given element.
-
-
-
- {{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
- Scrolls the page until the element gets into the view.
- {{ domxref("Element.setAttribute()") }}
- Sets the value of a named attribute of the current node.
- {{ domxref("Element.setAttributeNS()") }}
- Sets the value of the attribute with the specified name and namespace, from the current node.
- {{ domxref("Element.setAttributeNode()") }} {{Deprecated_Inline}}
- Sets the node representation of the named attribute from the current node.
- {{ domxref("Element.setAttributeNodeNS()") }} {{Deprecated_Inline}}
- Setw the node representation of the attribute with the specified name and namespace, from the current node.
- {{ domxref("Element.setCapture()") }} {{non-standard_inline}}
- Sets up mouse event capture, redirecting all mouse events to this element.
- {{domxref("Element.setPointerCapture()")}}
- Designates a specific element as the capture target of future {{domxref("PointerEvent","pointer events")}}.
-
-
-規範
+{{ APIRef("DOM") }}
+
+**`Element`** 介面表示了一個在 {{domxref("Document")}} 中的物件,其描述了各類型元素的共同屬性與方法,`Element` 的子介面則定義了不同類型元素的具體行為並增加額外的功能。例如 {{domxref("HTMLElement")}} 為所有 HTML 元素的基礎介面,而 {{domxref("SVGElement")}} 則是定義所有 SVG 元素的介面。
+
+在 Web 領域之外,如 XUL 語言也能藉由 `XULElement` 介面來繼承 `Element`。
+
+{{InheritanceDiagram}}
+
+## 屬性
+
+_Inherits properties from its parent interface, {{domxref("Node")}}, and by extension that interface's parent, {{domxref("EventTarget")}}. It implements the properties of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}},_ and {{domxref("Animatable")}}.
+
+- {{ domxref("Element.assignedSlot")}} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns the {{domxref("HTMLSlotElement")}} interface associated with the element.
+- {{ domxref("Element.attributes") }} {{readOnlyInline}}
+ - : Returns a {{ domxref("NamedNodeMap") }} object containing the assigned attributes of the corresponding HTML element.
+- {{ domxref("Element.classList") }} {{readOnlyInline}}
+ - : Returns a {{ domxref("DOMTokenList") }} containing the list of class attributes.
+- {{ domxref("Element.className") }}
+ - : Is a {{domxref("DOMString")}} representing the class of the element.
+- {{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the inner height of the element.
+- {{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the width of the left border of the element.
+- {{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the width of the top border of the element.
+- {{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the inner width of the element.
+- {{domxref("Element.computedName")}} {{readOnlyInline}}
+ - : Returns a {{domxref("DOMString")}} containing the label exposed to accessibility.
+- {{domxref("Element.computedRole")}} {{readOnlyInline}}
+ - : Returns a {{domxref("DOMString")}} containing the ARIA role that has been applied to a particular element.
+- {{ domxref("Element.id") }}
+ - : Is a {{domxref("DOMString")}} representing the id of the element.
+- {{ domxref("Element.innerHTML") }}
+ - : Is a {{domxref("DOMString")}} representing the markup of the element's content.
+- {{ domxref("Element.localName") }} {{readOnlyInline}}
+ - : A {{domxref("DOMString")}} representing the local part of the qualified name of the element.
+- {{domxref("Element.namespaceURI")}} {{readonlyInline}}
+ - : The namespace URI of the element, or `null` if it is no namespace.
+
+ > **備註:** In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the [`http://www.w3.org/1999/xhtml`](http://www.w3.org/1999/xhtml) namespace in both HTML and XML trees.
+- {{ domxref("NonDocumentTypeChildNode.nextElementSibling") }} {{readOnlyInline}}
+ - : Is a {{ domxref("Element") }}, the element immediately following the given one in the tree, or `null` if there's no sibling node.
+- {{ domxref("Element.outerHTML") }} {{experimental_inline}}
+ - : Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+- {{ domxref("Element.prefix") }} {{readOnlyInline}}
+ - : A {{domxref("DOMString")}} representing the namespace prefix of the element, or `null` if no prefix is specified.
+- {{ domxref("NonDocumentTypeChildNode.previousElementSibling") }} {{readOnlyInline}}
+ - : Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or `null` if there is no sibling element.
+- {{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+- {{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+ - : Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+- {{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+- {{ domxref("Element.scrollTop") }} {{experimental_inline}}
+ - : Is a {{jsxref("Number")}} representing the top scroll offset the an element.
+- {{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+- {{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+- {{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns the youngest shadow root that is hosted by the element.
+- {{domxref("Element.slot")}} {{experimental_inline}}
+ - : Returns the name of the shadow DOM slot attatched to the element. A slot is a placeholder inside a web component that users can fill with their own markup.
+- {{domxref("Element.tabStop")}} {{non-standard_inline}}
+ - : Is a {{jsxref("Boolean")}} indicating if the element can receive input focus via the tab key.
+- {{ domxref("Element.tagName") }} {{readOnlyInline}}
+ - : Returns a {{domxref("String")}} with the name of the tag for the given element.
+- {{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+ - : Returns the {{domxref("UndoManager")}} associated with the element.
+- {{ domxref("Element.undoScope")}} {{experimental_inline}}
+ - : Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
+
+> **備註:** DOM Level 3 defined `namespaceURI`, `localName` and `prefix` on the {{domxref("Node")}} interface. In DOM4 they were moved to `Element`.This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.
+
+### 事件處理器
+
+- {{ domxref("Element.ongotpointercapture") }}
+ - : Returns the event handler for the {{event("gotpointercapture")}} event type.
+- {{ domxref("Element.onlostpointercapture") }}
+ - : Returns the event handler for the {{event("lostpointercapture")}} event type.
+- {{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+ - : Returns the event handling code for the `wheel` event.
+
+## 方法
+
+_Inherits methods from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}_, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}_, {{domxref("NonDocumentTypeChildNode")}},_ _and {{domxref("Animatable")}}._
+
+- {{ domxref("EventTarget.addEventListener()") }}
+ - : Registers an event handler to a specific event type on the element.
+- {{domxref("Element.attachShadow()")}} {{experimental_inline}}
+ - : Attatches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}}.
+- {{domxref("Element.animate()")}} {{experimental_inline}}
+ - : A shortcut method to create and run an animation on an element. Returns the created Animation object instance.
+- {{ domxref("Element.closest()")}} {{experimental_inline}}
+ - : Returns the {{domxref("Element")}}, descendant of this element (or this element itself), that is the closest ancestor of the elements selected by the selectors given in parameter.
+- {{ domxref("Element.createShadowRoot()")}} {{experimental_inline}} {{deprecated_inline()}}
+ - : Creates a [shadow DOM](/zh-TW/docs/Web/Web_Components/Shadow_DOM) on on the element, turning it into a shadow host. Returns a {{domxref("ShadowRoot")}}.
+- {{ domxref("EventTarget.dispatchEvent()") }}
+ - : Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates that at least one handler has not canceled it.
+- {{domxref("Element.find()")}}{{experimental_inline}}
+ - : ...
+- {{domxref("Element.findAll()")}}{{experimental_inline}}
+ - : ...
+- {{domxref("Element.getAnimations()")}} {{experimental_inline}}
+ - : Returns an array of Animation objects currently active on the element.
+- {{ domxref("Element.getAttribute()") }}
+ - : Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
+- {{ domxref("Element.getAttributeNames()") }}
+ - : TBD
+- {{ domxref("Element.getAttributeNS()") }}
+ - : Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
+- {{ domxref("Element.getAttributeNode()") }} {{Deprecated_Inline}}
+ - : Retrieves the node representation of the named attribute from the current node and returns it as an {{ domxref("Attr") }}.
+- {{ domxref("Element.getAttributeNodeNS()") }} {{Deprecated_Inline}}
+ - : Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{ domxref("Attr") }}.
+- {{ domxref("Element.getBoundingClientRect()") }}
+ - : ...
+- {{ domxref("Element.getClientRects()") }}
+ - : Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+- {{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+ - : …
+- {{ domxref("Element.getElementsByClassName()") }}
+ - : Returns a live {{ domxref("HTMLCollection") }} that contains all descendants of the current element that possess the list of classes given in the parameter.
+- {{ domxref("Element.getElementsByTagName()") }}
+ - : Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
+- {{ domxref("Element.getElementsByTagNameNS()") }}
+ - : Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
+- {{ domxref("Element.hasAttribute()") }}
+ - : Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+- {{ domxref("Element.hasAttributeNS()") }}
+ - : Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+- {{ domxref("Element.hasAttributes()") }}
+ - : Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
+- {{ domxref("Element.insertAdjacentElement") }} {{experimental_inline}}
+ - : Inserts a given element node at a given position relative to the element it is invoked upon.
+- {{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+ - : Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+- {{ domxref("Element.insertAdjacentText") }} {{experimental_inline}}
+ - : Inserts a given text node at a given position relative to the element it is invoked upon.
+- {{ domxref("Element.matches()") }}` `{{experimental_inline}}
+ - : Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
+- {{ domxref("Element.querySelector()") }}
+ - : Returns the first {{ domxref("Node") }} which matches the specified selector string relative to the element.
+- {{ domxref("Element.querySelectorAll") }}
+ - : Returns a {{ domxref("NodeList") }} of nodes which match the specified selector string relative to the element.
+- {{ domxref("Element.releasePointerCapture")}}
+ - : Releases (stops) pointer capture that was previously set for a specific {{domxref("PointerEvent","pointer event")}}.
+- {{domxref("ChildNode.remove()")}} {{experimental_inline}}
+ - : Removes the element from the children list of its parent.
+- {{ domxref("Element.removeAttribute()") }}
+ - : Removes the named attribute from the current node.
+- {{ domxref("Element.removeAttributeNS()") }}
+ - : Removes the attribute with the specified name and namespace, from the current node.
+- {{ domxref("Element.removeAttributeNode()") }} {{Deprecated_Inline}}
+ - : Removes the node representation of the named attribute from the current node.
+- {{ domxref("EventTarget.removeEventListener()") }}
+ - : Removes an event listener from the element.
+- {{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+ - : Asynchronously asks the browser to make the element full-screen.
+- {{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+ - : Allows to asynchronously ask for the pointer to be locked on the given element.
+- {{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+ - : Scrolls the page until the element gets into the view.
+- {{ domxref("Element.setAttribute()") }}
+ - : Sets the value of a named attribute of the current node.
+- {{ domxref("Element.setAttributeNS()") }}
+ - : Sets the value of the attribute with the specified name and namespace, from the current node.
+- {{ domxref("Element.setAttributeNode()") }} {{Deprecated_Inline}}
+ - : Sets the node representation of the named attribute from the current node.
+- {{ domxref("Element.setAttributeNodeNS()") }} {{Deprecated_Inline}}
+ - : Setw the node representation of the attribute with the specified name and namespace, from the current node.
+- {{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+ - : Sets up mouse event capture, redirecting all mouse events to this element.
+- {{domxref("Element.setPointerCapture()")}}
+ - : Designates a specific element as the capture target of future {{domxref("PointerEvent","pointer events")}}.
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Element")}}
diff --git a/files/zh-tw/web/api/element/innerhtml/index.md b/files/zh-tw/web/api/element/innerhtml/index.md
index 3898b6d27f01b9..b12485df3e9b0e 100644
--- a/files/zh-tw/web/api/element/innerhtml/index.md
+++ b/files/zh-tw/web/api/element/innerhtml/index.md
@@ -8,159 +8,166 @@ tags:
- 裏超文本
translation_of: Web/API/Element/innerHTML
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
+[Element](/zh-TW/docs/Glossary/Element) 的「innerHTML」屬性獲取或設置元素中包含的 HTML 或 XML 標記。
+> **備註:** 如{{HTMLElement("div")}}, {{HTMLElement("span")}}, or {{HTMLElement("noembed")}} 節點有包含字符(&),(<)或(>),innerHTML 分別地回傳這些字符成為 HTML 的`“&” `,`“<” `和` “>” `。 使用 `Node.textContent` 得到的這些文本節點的內容的原始拷貝件。
- Element 的「innerHTML」屬性獲取或設置元素中包含的HTML或XML標記。
+To insert the HTML into the document rather than replace the contents of an element, use the method {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}.
-Note: 如{{HTMLElement("div")}}, {{HTMLElement("span")}}, or {{HTMLElement("noembed")}} 節點有包含字符(&),(<)或(>),innerHTML分別地回傳這些字符成為HTML的“&”
,“<”
和 “>”
。 使用 Node.textContent
得到的這些文本節點的內容的原始拷貝件。
+## Syntax
-To insert the HTML into the document rather than replace the contents of an element, use the method {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}.
+```js
+const content = element.innerHTML;
-Syntax
+element.innerHTML = htmlString;
+```
-const content = element .innerHTML;
+### Value
-element .innerHTML = htmlString ;
-
+A {{domxref("DOMString")}} containing the HTML serialization of the element's descendants. Setting the value of `innerHTML` removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string _htmlString_.
-Value
+### Exceptions
-A {{domxref("DOMString")}} containing the HTML serialization of the element's descendants. Setting the value of innerHTML
removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString .
+- `SyntaxError`
+ - : An attempt was made to set the value of `innerHTML` using a string which is not properly-formed HTML.
+- `NoModificationAllowedError`
+ - : An attempt was made to insert the HTML into a node whose parent is a {{domxref("Document")}}.
-Exceptions
+## Usage notes
-
- SyntaxError
- An attempt was made to set the value of innerHTML
using a string which is not properly-formed HTML.
- NoModificationAllowedError
- An attempt was made to insert the HTML into a node whose parent is a {{domxref("Document")}}.
-
+The `innerHTML` property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.
-Usage notes
+### Reading the HTML contents of an element
-The innerHTML
property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.
+Reading `innerHTML` causes the user agent to serialize the HTML or XML fragment comprised of the elment's descendants. The resulting string is returned.
-Reading the HTML contents of an element
+```js
+let contents = myElement.innerHTML;
+```
-Reading innerHTML
causes the user agent to serialize the HTML or XML fragment comprised of the elment's descendants. The resulting string is returned.
+This lets you look at the HTML markup of the element's content nodes.
-let contents = myElement.innerHTML;
+> **備註:** The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
-This lets you look at the HTML markup of the element's content nodes.
+> **備註:** 基於元素的當前內容產生返回的 HTML 或 XML 片段,所以返回的片段的標記和格式可能不匹配原始頁面標記。
-
-
Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
-
-
-
-
Note: 基於元素的當前內容產生返回的HTML或XML片段,所以返回的片段的標記和格式可能不匹配原始頁面標記。
-
+### Replacing the contents of an element
-Replacing the contents of an element
+Setting the value of `innerHTML` lets you easily replace the existing contents of an element with new content.
-Setting the value of innerHTML
lets you easily replace the existing contents of an element with new content.
+For example, you can erase the entire contents of a document by clearing the contents of the document's {{domxref("Document.body", "body")}} attribute:
-For example, you can erase the entire contents of a document by clearing the contents of the document's {{domxref("Document.body", "body")}} attribute:
+```js
+document.body.innerHTML = "";
+```
-document.body.innerHTML = "";
+This example fetches the document's current HTML markup and replaces the `"<"` characters with the HTML entity `"<"`, thereby essentially converting the HTML into raw text. This is then wrapped in a {{HTMLElement("pre")}} element. Then the value of `innerHTML` is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.
-This example fetches the document's current HTML markup and replaces the "<"
characters with the HTML entity "<"
, thereby essentially converting the HTML into raw text. This is then wrapped in a {{HTMLElement("pre")}} element. Then the value of innerHTML
is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.
+```js
+document.documentElement.innerHTML = "" +
+ document.documentElement.innerHTML.replace(/";
+```
-document.documentElement.innerHTML = "<pre>" +
- document.documentElement.innerHTML.replace(/</g,"<") +
- "</pre>";
+#### Operational details
-Operational details
+What exactly happens when you set value of `innerHTML`? Doing so causes the user agent to follow these steps:
-What exactly happens when you set value of innerHTML
? Doing so causes the user agent to follow these steps:
+1. The specified value is parsed as HTML or XML (based on the document type), resulting in a {{domxref("DocumentFragment")}} object representing the new set of DOM nodes for the new elements.
+2. If the element whose contents are being replaced is a {{HTMLElement("template")}} element, then the `` element's {{domxref("HTMLTemplateElement.content", "content")}} attribute is replaced with the new `DocumentFragment` created in step 1.
+3. For all other elements, the element's contents are replaced with the nodes in the new `DocumentFragment`.
-
- The specified value is parsed as HTML or XML (based on the document type), resulting in a {{domxref("DocumentFragment")}} object representing the new set of DOM nodes for the new elements.
- If the element whose contents are being replaced is a {{HTMLElement("template")}} element, then the <template>
element's {{domxref("HTMLTemplateElement.content", "content")}} attribute is replaced with the new DocumentFragment
created in step 1.
- For all other elements, the element's contents are replaced with the nodes in the new DocumentFragment
.
-
+### Security considerations
-Security considerations
+It is not uncommon to see `innerHTML` used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.
-It is not uncommon to see innerHTML
used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.
-
-const name = "John";
+```js
+const name = "John";
// assuming 'el' is an HTML DOM element
el.innerHTML = name; // harmless in this case
// ...
-name = "<script>alert('I am John in an annoying alert!')</script>";
-el.innerHTML = name; // harmless in this case
+name = "";
+el.innerHTML = name; // harmless in this case
+```
-Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a {{HTMLElement("script")}} tag inserted with innerHTML
should not execute .
+Although this may look like a [cross-site scripting](https://zh.wikipedia.org/wiki/cross-site_scripting) attack, the result is harmless. HTML5 specifies that a {{HTMLElement("script")}} tag inserted with `innerHTML` [should not execute](https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0).
-However, there are ways to execute JavaScript without using {{HTMLElement("script")}} elements, so there is still a security risk whenever you use innerHTML
to set strings over which you have no control. For example:
+However, there are ways to execute JavaScript without using {{HTMLElement("script")}} elements, so there is still a security risk whenever you use `innerHTML` to set strings over which you have no control. For example:
-const name = "<img src='x' onerror='alert(1)'>";
-el.innerHTML = name; // shows the alert
+```js
+const name = " ";
+el.innerHTML = name; // shows the alert
+```
-For that reason, it is recommended that you do not use innerHTML
when inserting plain text; instead, use {{domxref("Node.textContent")}}. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
+For that reason, it is recommended that you do not use `innerHTML` when inserting plain text; instead, use {{domxref("Node.textContent")}}. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
-
-
Warning: If your project is one that will undergo any form of security review, using innerHTML
most likely will result in your code being rejected. For example, if you use innerHTML
in a browser extension and submit the extension to addons.mozilla.org , it will not pass the automated review process.
-
+> **警告:** If your project is one that will undergo any form of security review, using `innerHTML` most likely will result in your code being rejected. For example, [if you use `innerHTML`](https://wiki.mozilla.org/Add-ons/Reviewers/Guide/Reviewing#Step_2:_Automatic_validation) in a [browser extension](/zh-TW/docs/Mozilla/Add-ons/WebExtensions) and submit the extension to [addons.mozilla.org](https://addons.mozilla.org/), it will not pass the automated review process.
-Example
+## Example
-This example uses innerHTML
to create a mechanism for logging messages into a box on a web page.
+This example uses `innerHTML` to create a mechanism for logging messages into a box on a web page.
-JavaScript
+### JavaScript
-function log(msg) {
+```js
+function log(msg) {
var logElem = document.querySelector(".log");
var time = new Date();
var timeStr = time.toLocaleTimeString();
- logElem.innerHTML += timeStr + ": " + msg + "<br/>";
+ logElem.innerHTML += timeStr + ": " + msg + " ";
}
log("Logging mouse events inside this container...");
-
+```
-The log()
function creates the log output by getting the current time from a {{jsxref("Date")}} object using {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}}, and building a string with the timestamp and the message text. Then the message is appended to the box with the class "log"
.
+The `log()` function creates the log output by getting the current time from a {{jsxref("Date")}} object using {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}}, and building a string with the timestamp and the message text. Then the message is appended to the box with the class `"log"`.
-We add a second method that logs information about {{domxref("MouseEvent")}} based events (such as {{event("mousedown")}}, {{event("click")}}, and {{event("mouseenter")}}):
+We add a second method that logs information about {{domxref("MouseEvent")}} based events (such as {{event("mousedown")}}, {{event("click")}}, and {{event("mouseenter")}}):
-function logEvent(event) {
- var msg = "Event <strong>" + event.type + "</strong> at <em>" +
- event.clientX + ", " + event.clientY + "</em>";
+```js
+function logEvent(event) {
+ var msg = "Event " + event.type + " at " +
+ event.clientX + ", " + event.clientY + " ";
log(msg);
-}
+}
+```
-Then we use this as the event handler for a number of mouse events on the box that contains our log:
+Then we use this as the event handler for a number of mouse events on the box that contains our log:
-var boxElem = document.querySelector(".box");
+```js
+var boxElem = document.querySelector(".box");
boxElem.addEventListener("mousedown", logEvent);
boxElem.addEventListener("mouseup", logEvent);
boxElem.addEventListener("click", logEvent);
boxElem.addEventListener("mouseenter", logEvent);
-boxElem.addEventListener("mouseleave", logEvent);
+boxElem.addEventListener("mouseleave", logEvent);
+```
-HTML
+### HTML
-The HTML is quite simple for our example.
+The HTML is quite simple for our example.
-<div class="box">
- <div><strong>Log:</strong></div>
- <div class="log"></div>
-</div>
+```html
+
+```
-The {{HTMLElement("div")}} with the class "box"
is just a container for layout purposes, presenting the contents with a box around it. The <div>
whose class is "log"
is the container for the log text itself.
+The {{HTMLElement("div")}} with the class `"box"` is just a container for layout purposes, presenting the contents with a box around it. The `` whose class is `"log"` is the container for the log text itself.
-
CSS
+### CSS
-
The following CSS styles our example content.
+The following CSS styles our example content.
-
.box {
+```css
+.box {
width: 600px;
height: 300px;
border: 1px solid black;
@@ -172,29 +179,26 @@ boxElem.addEventListener("mouseleave", logEvent);
.log {
margin-top: 8px;
font-family: monospace;
-}
+}
+```
-
Result
+### Result
-
The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.
+The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.
-
{{EmbedLiveSample("Example", 640, 350)}}
+{{EmbedLiveSample("Example", 640, 350)}}
-
Specification
+## Specification
{{Specifications}}
-
Browser compatibility
-
-
+## Browser compatibility
-
{{Compat("api.Element.innerHTML")}}
+{{Compat("api.Element.innerHTML")}}
-
See also
+## See also
-
- {{domxref("Node.textContent")}} and {{domxref("Node.innerText")}}
- {{domxref("Element.insertAdjacentHTML()")}}
- Parsing HTML into a DOM tree: {{domxref("DOMParser")}}
- Serializing XML or HTML into a DOM tree: {{domxref("XMLSerializer")}}
-
+- {{domxref("Node.textContent")}} and {{domxref("Node.innerText")}}
+- {{domxref("Element.insertAdjacentHTML()")}}
+- Parsing HTML into a DOM tree: {{domxref("DOMParser")}}
+- Serializing XML or HTML into a DOM tree: {{domxref("XMLSerializer")}}
diff --git a/files/zh-tw/web/api/element/insertadjacenthtml/index.md b/files/zh-tw/web/api/element/insertadjacenthtml/index.md
index 7c8eca7d25ab0c..0984b96c076d30 100644
--- a/files/zh-tw/web/api/element/insertadjacenthtml/index.md
+++ b/files/zh-tw/web/api/element/insertadjacenthtml/index.md
@@ -3,72 +3,70 @@ title: Element.insertAdjacentHTML()
slug: Web/API/Element/insertAdjacentHTML
translation_of: Web/API/Element/insertAdjacentHTML
---
-
{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-
insertAdjacentHTML()
把傳入的字串解析成 HTML 或 XML,並把該節點插入到 DOM 樹指定的位置。它不會重新解析被使用的元素,因此他不會破壞該元素裡面原有的元素。這避免了序列化的複雜步驟,使得它比直接操作 innerHTML
快上許多。
+`insertAdjacentHTML()` 把傳入的字串解析成 HTML 或 XML,並把該節點插入到 DOM 樹指定的位置。它不會重新解析被使用的元素,因此他不會破壞該元素裡面原有的元素。這避免了序列化的複雜步驟,使得它比直接操作 `innerHTML` 快上許多。
-
Syntax
+## Syntax
-
element .insertAdjacentHTML(position , text );
+```js
+element.insertAdjacentHTML(position, text);
+```
-
Parameters
+### Parameters
-
- position
- A {{domxref("DOMString")}} representing the position relative to the element
; must be one of the following strings:
-
- 'beforebegin'
: 在 element
之前。
- 'afterbegin'
: 在 element
裡面,第一個子元素之前。
- 'beforeend'
: 在 element
裡面,最後一個子元素之後。
- 'afterend'
: 在 element
之後。
-
-
- text
- text
是即將被解析並插入到 DOM 樹裡的字串。
-
+- position
+ - : A {{domxref("DOMString")}} representing the position relative to the `element`; must be one of the following strings: `'beforebegin'`: 在 `element` 之前。
+ - `'afterbegin'`: 在 `element` 裡面,第一個子元素之前。
+ - `'beforeend'`: 在 `element` 裡面,最後一個子元素之後。
+ - `'afterend'`: 在 `element` 之後。
+- text
+ - : `text` 是即將被解析並插入到 DOM 樹裡的字串。
-
Visualization of position names
+### Visualization of position names
-
<!-- beforebegin -->
-<p>
- <!-- afterbegin -->
+```html
+
+
+
foo
- <!-- beforeend -->
-</p>
-<!-- afterend -->
+
+
+
+```
-
Note: beforebegin
和 afterend
只在該節點位於 DOM 樹內、並且有母元素時有效。
+> **備註:** `beforebegin` 和 `afterend` 只在該節點位於 DOM 樹內、並且有母元素時有效。
-
Example
+## Example
-
// <div id="one">one</div>
+```js
+// one
var d1 = document.getElementById('one');
-d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+d1.insertAdjacentHTML('afterend', 'two
');
// At this point, the new structure is:
-// <div id="one">one</div><div id="two">two</div>
+//
one
two
+```
-
Notes
+## Notes
-
Security Considerations
+### Security Considerations
-
When inserting HTML into a page by using insertAdjacentHTML
be careful not to use user input that hasn't been escaped.
+When inserting HTML into a page by using `insertAdjacentHTML` be careful not to use user input that hasn't been escaped.
-
It is not recommended you use insertAdjacentHTML
when inserting plain text; instead, use the Node.textContent
property or Element.insertAdjacentText()
method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.
+It is not recommended you use `insertAdjacentHTML` when inserting plain text; instead, use the [`Node.textContent`](/zh-TW/docs/Web/API/Node/textContent) property or [`Element.insertAdjacentText()`](/zh-TW/docs/Web/API/Element/insertAdjacentText) method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.
-
Specification
+## Specification
{{Specifications}}
-
Browser compatibility
+## Browser compatibility
{{Compat("api.Element.insertAdjacentHTML")}}
-
See also
+## See also
-
- {{domxref("Element.insertAdjacentElement()")}}
- {{domxref("Element.insertAdjacentText()")}}
- {{domxref("XMLSerializer")}}: Construct a DOM representation of XML text
- hacks.mozilla.org guest post by Henri Sivonen including benchmark showing that insertAdjacentHTML can be way faster in some cases.
-
+- {{domxref("Element.insertAdjacentElement()")}}
+- {{domxref("Element.insertAdjacentText()")}}
+- {{domxref("XMLSerializer")}}: Construct a DOM representation of XML text
+- [hacks.mozilla.org guest post](https://hacks.mozilla.org/2011/11/insertadjacenthtml-enables-faster-html-snippet-injection/) by Henri Sivonen including benchmark showing that insertAdjacentHTML can be way faster in some cases.
diff --git a/files/zh-tw/web/api/element/scrollheight/index.md b/files/zh-tw/web/api/element/scrollheight/index.md
index a7cab6303e1cef..bf74f3a656f998 100644
--- a/files/zh-tw/web/api/element/scrollheight/index.md
+++ b/files/zh-tw/web/api/element/scrollheight/index.md
@@ -6,54 +6,54 @@ tags:
- Reference
translation_of: Web/API/Element/scrollHeight
---
-
{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-
Element.scrollHeight
是衡量元素包含因為 overflow 而沒顯示在螢幕上的內容高度的唯讀屬性. scrollHeight
的值相等於元素要求 clientHeight
在視域中沒有使用滾動條顯示所有內容的最小高度值 . 這當中只包含 padding, 並不包含 margin.
+**`Element.scrollHeight`** 是衡量元素包含因為 overflow 而沒顯示在螢幕上的內容高度的唯讀屬性. `scrollHeight` 的值相等於元素要求 `clientHeight` 在視域中沒有使用滾動條顯示所有內容的最小高度值 . 這當中只包含 padding, 並不包含 margin.
-
-
這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("Element.getBoundingClientRect()") }}.
-
+> **備註:** 這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("Element.getBoundingClientRect()") }}.
-
表達式
+## 表達式
-
var intElemScrollHeight = document.getElementById(id_attribute_value ).scrollHeight;
-
+```js
+var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
+```
-
intElemScrollHeight 是個儲存了元素 scrollHeight 的正整數變數. scrollHeight是唯讀的屬性.
+_intElemScrollHeight_ 是個儲存了元素 scrollHeight 的正整數變數. scrollHeight 是唯讀的屬性.
-
範例
+## 範例
-
-
-
padding-top
+padding-top
-
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
+Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
-
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-
padding-bottom
-
-
Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+padding-bottom
-
+**Left** **Top** **Right** **Bottom** _margin-top_ _margin-bottom_ _border-top_ _border-bottom_
-
問題與解決方法
+![Image:scrollHeight.png](/@api/deki/files/840/=ScrollHeight.png)
-
了解元素是否被滾輪完全滾過
+## 問題與解決方法
-
下面的等式代表如果元素被完全滾過將會
回傳 true
, 否則回傳 false
.
+### 了解元素是否被滾輪完全滾過
-
element.scrollHeight - element.scrollTop === element.clientHeight
+下面的等式代表`如果元素被完全滾過將會`回傳 `true `, 否則回傳 `false`.
-
+```js
+element.scrollHeight - element.scrollTop === element.clientHeight
+```
-
藉由 onscroll
事件, 這個等式對於決定使用者是否已經讀完文字內容是很有用 (參見 element.scrollTop
, element.clientHeight
屬性). 範例:
+## scrollHeight 範例
-
HTML
+藉由 [`onscroll`](/en-US/docs/DOM/element.onscroll) 事件, 這個等式對於決定使用者是否已經讀完文字內容是很有用 (參見 [`element.scrollTop`](/en-US/docs/DOM/element.scrollTop), [`element.clientHeight`](/en-US/docs/DOM/element.clientHeight) 屬性). 範例:
-
<form name="registration">
- <p>
- <textarea id="rules">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at laoreet magna.
+### HTML
+
+```html
+
+```
+
+### CSS
+
+```css
+#notice {
display: inline-block;
margin-bottom: 12px;
border-radius: 5px;
@@ -101,11 +103,13 @@ nascetur ridiculus mus. Cras vulputate libero sed arcu iaculis nec lobortis orci
padding: 5px;
border: #2A9F00 solid 2px;
border-radius: 5px;
-}
+}
+```
-
JavaScript
+### JavaScript
-
function checkReading () {
+```js
+function checkReading () {
if (checkReading.read) {
return;
}
@@ -123,23 +127,22 @@ onload = function () {
oToBeRead.parentNode.insertBefore(document.createElement("br"), oToBeRead);
oToBeRead.onscroll = checkReading;
checkReading.call(oToBeRead);
-}
+}
+```
-
{{ EmbedLiveSample('scrollHeight_Demo', '640', '400') }}
+{{ EmbedLiveSample('scrollHeight_Demo', '640', '400') }}
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat}}
-
參見
+## 參見
-
+- [MSDN: Measuring Element Dimension and Location with CSSOM in Windows Internet Explorer 9](
)
+- {{domxref("Element.clientHeight")}}
+- {{domxref("Element.offsetHeight")}}
+- [Determining the dimensions of elements](/zh-TW/docs/Determining_the_dimensions_of_elements)
diff --git a/files/zh-tw/web/api/element/scrolltop/index.md b/files/zh-tw/web/api/element/scrolltop/index.md
index f35630fedc9ffd..9a4ec7162f0c15 100644
--- a/files/zh-tw/web/api/element/scrolltop/index.md
+++ b/files/zh-tw/web/api/element/scrolltop/index.md
@@ -7,54 +7,50 @@ tags:
- Reference
translation_of: Web/API/Element/scrollTop
---
-{{ APIRef("DOM") }}
+{{ APIRef("DOM") }}
-Element.scrollTop
屬性可以設置和獲取元素被向上捲動的高度(pixels). 元素的 scrollTop
是元素頂端和能被看見的最頂端之間的距離. 當元素並未產生滾動條, 那麼 scrollTop
的值預設為 0
.
+**`Element.scrollTop`** 屬性可以設置和獲取元素被向上捲動的高度(pixels). 元素的 `scrollTop` 是元素頂端和能被看見的最頂端之間的距離. 當元素並未產生滾動條, 那麼 `scrollTop` 的值預設為 `0`.
-表達式
+## 表達式
-// 獲得已經被滾動的距離(pixels)
-var intElemScrollTop = someElement.scrollTop;
-
+```js
+// 獲得已經被滾動的距離(pixels)
+var intElemScrollTop = someElement.scrollTop;
+```
-intElemScrollTop
為 {{domxref("element")}}已經被滾動的距離(pixels ).
+`intElemScrollTop` 為 {{domxref("element")}}已經被滾動的距離(pixels ).
-// 設置已經被滾動的距離(pixels)
-element .scrollTop = intValue ;
-
+```js
+// 設置已經被滾動的距離(pixels)
+element.scrollTop = intValue;
+```
-scrollTop
可以被設置為任何和正整數, 注意事項:
+`scrollTop` 可以被設置為任何和正整數, 注意事項:
-
- 如果元素不能滾動, scrollTop
被設置為 0
.
- 如果設置的值小於 0
, scrollTop
被設置為 0
.
- 如果設置的值大於內容可以被滾動的距離, scrollTop
被設置為最大值.
-
+- 如果元素不能滾動, `scrollTop` 被設置為 `0`.
+- 如果設置的值小於 `0`, `scrollTop` 被設置為 `0`.
+- 如果設置的值大於內容可以被滾動的距離, `scrollTop` 被設置為最大值.
-範例
+## 範例
-
-
-
padding-top
+padding-top
-
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
+Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
-
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-
padding-bottom
-
-
Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+padding-bottom
-
+**Left** **Top** **Right** **Bottom** _margin-top_ _margin-bottom_ _border-top_ _border-bottom_
-規範
+![Image:scrollTop.png](/@api/deki/files/842/=ScrollTop.png)
+
+## 規範
{{Specifications}}
-參閱
+## 參閱
-
+- [W3C Draft CSSOM View Module](http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop)
+- [MSDN's scrollTop definition]()
+- [MSDN's Measuring Element Dimension and Location]()
diff --git a/files/zh-tw/web/api/event/comparison_of_event_targets/index.md b/files/zh-tw/web/api/event/comparison_of_event_targets/index.md
index 2f4fd206e42170..5651ba5e328afe 100644
--- a/files/zh-tw/web/api/event/comparison_of_event_targets/index.md
+++ b/files/zh-tw/web/api/event/comparison_of_event_targets/index.md
@@ -3,69 +3,36 @@ title: Comparison of Event Targets
slug: Web/API/Event/Comparison_of_Event_Targets
translation_of: Web/API/Event/Comparison_of_Event_Targets
---
-{{ ApiRef() }}
-
-Event targets
-
-It's easy to get confused about which target to examine when writing an event handler. This article should clarify the use of the target properties.
-
-There are 5 targets to consider:
-
-
+{{ ApiRef() }}
+
+### Event targets
+
+It's easy to get confused about which target to examine when writing an event handler. This article should clarify the use of the target properties.
+
+There are 5 targets to consider:
+
+| Property | Defined in | Purpose |
+| ------------------------------------ | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
+| [event.target](/en/DOM/event.target) | [DOM Event Interface](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface) | The DOM element on the lefthand side of the call that triggered this event, eg: `element.dispatchEvent(event)`|
+| [event.currentTarget](/en/DOM/event.currentTarget) | [DOM Event Interface](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface) | The [`EventTarget`](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget) whose [`EventListeners`](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener) are currently being processed. As the event capturing and bubbling occurs this value changes. |
+| [event.relatedTarget](/en/DOM/event.relatedTarget) | [DOM MouseEvent Interface](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent) | Identifies a secondary target for the event. |
+| [event.explicitOriginalTarget](/en/DOM/event.explicitOriginalTarget) | [Event.webidl](https://dxr.mozilla.org/mozilla-central/source/dom/webidl/Event.webidl) | {{ Non-standard_inline() }} If the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. For example, mouse events are retargeted to their parent node when they happen over text nodes ({{ Bug("185889") }}), and in that case `.target` will show the parent and `.explicitOriginalTarget` will show the text node. Unlike `.originalTarget`, `.explicitOriginalTarget` will never contain anonymous content. |
+| [event.originalTarget](/en/DOM/event.originalTarget) | [Event.webidl](https://dxr.mozilla.org/mozilla-central/source/dom/webidl/Event.webidl) | {{ Non-standard_inline() }} The original target of the event, before any retargetings. See [Anonymous Content#Event_Flow_and_Targeting](/zh-TW/docs/XBL/XBL_1.0_Reference/Anonymous_Content#Event_Flow_and_Targeting) for details. |
-Use of explicitOriginalTarget
and originalTarget
+### Use of `explicitOriginalTarget` and `originalTarget`
-TODO: Only available in a Mozilla-based browser? TODO: Only suitable for extension-developers?
+TODO: Only available in a Mozilla-based browser? TODO: Only suitable for extension-developers?
-範例
+### 範例
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>Comparison of Event Targets</title>
- <style>
+```html
+
+
+
+
+
+ Comparison of Event Targets
+
+
+
+
+
+
+ Original target dispatching the event event.target
+ Target who's event listener is being processed event.currentTarget
+ Identify other element (if any) involved in the event event.relatedTarget
+ If there was a retargetting of the event for some reason event.explicitOriginalTarget contains the target before retargetting (never contains anonymous targets)
+ If there was a retargetting of the event for some reason event.originalTarget contains the target before retargetting (may contain anonymous targets)
+
+
+
+
+
+
+
+
+
+
+Clicking on the text will show the difference between explicitOriginalTarget, originalTarget and target
+
+
+
+```
+
+### Use of `target` and `relatedTarget`
+
+The `relatedTarget` property for the `mouseover` event holds the node that the mouse was previously over. For the `mouseout` event, it holds the node that the mouse moved to.
-TODO: Also needs descriptions about dragenter
and dragexit
events.
+| Event type | [event.target](/en/DOM/event.target) | [event.relatedTarget](/en/DOM/event.relatedTarget) |
+| ----------- | ------------------------------------------------- | -------------------------------------------------- |
+| `mouseover` | the EventTarget which the pointing device entered | the EventTarget which the pointing device exited |
+| `mouseout` | the EventTarget which the pointing device exited | the EventTarget which the pointing device entered |
-範例
+TODO: Also needs descriptions about `dragenter` and `dragexit` events.
-<hbox id="outer">
- <hbox id="inner"
- onmouseover="dump('mouseover ' + event.relatedTarget.id + ' > ' + event.target.id + '\n');"
- onmouseout="dump('mouseout ' + event.target.id + ' > ' + event.relatedTarget.id + '\n');"
- style="margin: 100px; border: 10px solid black; width: 100px; height: 100px;" />
-</hbox>
-
+#### 範例
-
+```html
+
+
+
+```
diff --git a/files/zh-tw/web/api/event/defaultprevented/index.md b/files/zh-tw/web/api/event/defaultprevented/index.md
index 49e9f3f152a17d..6d9e264a5be8db 100644
--- a/files/zh-tw/web/api/event/defaultprevented/index.md
+++ b/files/zh-tw/web/api/event/defaultprevented/index.md
@@ -3,29 +3,32 @@ title: Event.defaultPrevented
slug: Web/API/Event/defaultPrevented
translation_of: Web/API/Event/defaultPrevented
---
-{{ APIRef("DOM") }}
+{{ APIRef("DOM") }}
-概述
+## 概述
-回傳一個布林值,表示事件的預設行為是否被取消,也就是事件物件是否曾執行 {{domxref("event.preventDefault()", "preventDefault()")}} 方法。
+回傳一個布林值,表示事件的預設行為是否被取消,也就是事件物件是否曾執行 {{domxref("event.preventDefault()", "preventDefault()")}} 方法。
-註: You should use this instead of the non-standard, deprecated getPreventDefault()
method (see {{ bug(691151) }}).
+> **備註:** You should use this instead of the non-standard, deprecated` getPreventDefault()` method (see {{ bug(691151) }}).
-語法
+## 語法
-bool = event.defaultPrevented
+```js
+bool = event.defaultPrevented
+```
-範例
+## 範例
- if (e.defaultPrevented) {
+```js
+ if (e.defaultPrevented) {
/* the default was prevented */
}
-
+```
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Event.defaultPrevented")}}
diff --git a/files/zh-tw/web/api/event/index.md b/files/zh-tw/web/api/event/index.md
index b56afc9b74cf66..06ead5d061a8db 100644
--- a/files/zh-tw/web/api/event/index.md
+++ b/files/zh-tw/web/api/event/index.md
@@ -12,186 +12,161 @@ tags:
- TopicStub
translation_of: Web/API/Event
---
-{{APIRef("DOM")}}
-
-Event
介面表示了一個在 DOM 物件上所發生的事件。
-
-一個事件可以是由使用者的操作行為所產生(如:點擊滑鼠按鈕或敲打鍵盤),或是來自 API 因處理非同步任務所產生。事件也可以為程式所觸發,例如呼叫元素的 HTMLElement.click()
方法,或是自行定義事件並使用 EventTarget.dispatchEvent()
發送至特定的目標。
-
-事件有多種不同的類型,部分事件是使用基於 Event
的子介面。Event
本身包含了所有事件共同的屬性及方法。
-
-許多 DOM 元素可被設定接受(accept,或稱為 listen "監聽")這些事件,並在發生時執行處理(process、handle)事件的程式碼。事件處理器(Event-handlers)通常會使用 EventTarget.addEventListener()
來被連結(connected,或稱為 attached "附加")至各個 HTML 元素 (例如 <button>、<div>、<div>、<span> 等),且此方式一般也是用來取代舊的 HTML 事件處理器屬性(attributes) 。此外,在需要時也可以使用 removeEventListener()
來中斷事件處理器與元素的連結。請留意一個元素可以擁有多個事件處理器(即使是處理同一種事件的不同處理器),特別是那些被切分開來彼此獨立且有不同目標的程式模組(舉例來說,廣告及統計模組可以同時監控網頁中的影片觀看資訊)。
-
-When there are many nested elements, each with its own handler(s), event processing can become very complicated -- especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the Event bubbling and capture settings of each handler triggered.
-
-基於 Event
的子介面
-
-Below is a list of interfaces which are based on the main Event
interface, with links to their respective documentation in the MDN API reference. Note that all event interfaces have names which end in "Event".
-
-
-
- {{domxref("AnimationEvent")}}
- {{domxref("AudioProcessingEvent")}}
- {{domxref("BeforeInputEvent")}}
- {{domxref("BeforeUnloadEvent")}}
- {{domxref("BlobEvent")}}
- {{domxref("ClipboardEvent")}}
- {{domxref("CloseEvent")}}
- {{domxref("CompositionEvent")}}
- {{domxref("CSSFontFaceLoadEvent")}}
- {{domxref("CustomEvent")}}
- {{domxref("DeviceLightEvent")}}
- {{domxref("DeviceMotionEvent")}}
- {{domxref("DeviceOrientationEvent")}}
- {{domxref("DeviceProximityEvent")}}
- {{domxref("DOMTransactionEvent")}}
- {{domxref("DragEvent")}}
- {{domxref("EditingBeforeInputEvent")}}
- {{domxref("ErrorEvent")}}
- {{domxref("FetchEvent")}}
- {{domxref("FocusEvent")}}
- {{domxref("GamepadEvent")}}
- {{domxref("HashChangeEvent")}}
- {{domxref("IDBVersionChangeEvent")}}
- {{domxref("InputEvent")}}
- {{domxref("KeyboardEvent")}}
- {{domxref("MediaStreamEvent")}}
- {{domxref("MessageEvent")}}
- {{domxref("MouseEvent")}}
- {{domxref("MutationEvent")}}
- {{domxref("OfflineAudioCompletionEvent")}}
- {{domxref("OverconstrainedError")}}
- {{domxref("PageTransitionEvent")}}
- {{domxref("PaymentRequestUpdateEvent")}}
- {{domxref("PointerEvent")}}
- {{domxref("PopStateEvent")}}
- {{domxref("ProgressEvent")}}
- {{domxref("RelatedEvent")}}
- {{domxref("RTCDataChannelEvent")}}
- {{domxref("RTCIdentityErrorEvent")}}
- {{domxref("RTCIdentityEvent")}}
- {{domxref("RTCPeerConnectionIceEvent")}}
- {{domxref("SensorEvent")}}
- {{domxref("StorageEvent")}}
- {{domxref("SVGEvent")}}
- {{domxref("SVGZoomEvent")}}
- {{domxref("TimeEvent")}}
- {{domxref("TouchEvent")}}
- {{domxref("TrackEvent")}}
- {{domxref("TransitionEvent")}}
- {{domxref("UIEvent")}}
- {{domxref("UserProximityEvent")}}
- {{domxref("WebGLContextEvent")}}
- {{domxref("WheelEvent")}}
-
-
-
-建構式
-
-
- {{domxref("Event.Event", "Event()")}}
- 建立一個 Event
物件。
-
-
-屬性
-
-
- {{domxref("Event.bubbles")}} {{readonlyinline}}
- 布林值,表示事件是否會向上冒泡傳遞。
- {{domxref("Event.cancelBubble")}}
- 由於歷史性因素,此屬性的效果等同於 {{domxref("Event.stopPropagation()", "stopPropagation()")}} 方法。若在事件處理器回傳前設定此值為 true
,可阻止事件繼續向上冒泡傳遞。
- {{domxref("Event.cancelable")}} {{readonlyinline}}
- 布林值,表示事件是否能被取消。
- {{domxref("Event.composed")}} {{ReadOnlyInline}}
- A Boolean value indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.
- {{domxref("Event.currentTarget")}} {{readonlyinline}}
- 指向目前處理事件之監聽器所屬的 DOM 物件。
- {{domxref("Event.deepPath")}} {{non-standard_inline}}
- An {{jsxref("Array")}} of DOM {{domxref("Node")}}s through which the event has bubbled.
- {{domxref("Event.defaultPrevented")}} {{readonlyinline}}
- 布林值,表示事件的預設行為是否被 {{domxref("event.preventDefault()", "preventDefault()")}} 方法所取消。
- {{domxref("Event.eventPhase")}} {{readonlyinline}}
- 表示事件目前的傳遞階段。
- {{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
- 事件的明確原定目標(Mozilla 專屬)。
- {{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
- 事件重新導向前的原定目標(Mozilla 專屬)。
- {{domxref("Event.returnValue")}}
- 非標準屬性。用以替代 {{domxref("Event.preventDefault()", "preventDefault()")}} 方法與 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性(舊版 Internet Explorer 專屬)。
- {{domxref("Event.scoped")}} {{readonlyinline}} {{Deprecated_Inline}}
- A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
- {{domxref("Event.srcElement")}} {{non-standard_inline}}
- 非標準屬性。為 {{domxref("Event.target", "target")}} 屬性的別名(舊版 Internet Explorer 專屬)。
- {{domxref("Event.target")}} {{readonlyinline}}
- 指向最初觸發事件的 DOM 物件。
- {{domxref("Event.timeStamp")}} {{readonlyinline}}
- 事件發生(事件物件建立)至今的時間。
- {{domxref("Event.type")}} {{readonlyinline}}
- 事件類型(不區分大小寫)。
- {{domxref("Event.isTrusted")}} {{readonlyinline}}
- 表示事件物件是否為瀏覽器建立(比如在用戶點擊之後),或由程式碼所建立(使用建立事件的方法,如 {{domxref("Event.initEvent()", "initEvent()")}})。
-
-
-Obsolete properties
-
-
- {{domxref("Event.scoped")}} {{readonlyinline}} {{Deprecated_Inline}}
- A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
-
-
-方法
-
-
- {{domxref("Event.createEvent()")}} {{deprecated_inline}}
-
- Creates a new event, which must then be initialized by calling its initEvent()
method.
-
- {{domxref("Event.composedPath()")}}
- Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its {{domxref("ShadowRoot.mode")}} closed.
-
-
-
- {{domxref("Event.initEvent()")}} {{deprecated_inline}}
- 初始化已經建立的事件。若該事件已經被處理過,這方法就不會執行任何東西。
- {{domxref("Event.preventDefault()")}}
- 取消該事件(如果該事件的 {{domxref("Event.cancelable", "cancelable")}} 屬性為 true
)。
- {{domxref("Event.stopImmediatePropagation()")}}
- 一旦事件物件呼叫此方法,目前元素中尚未執行的已註冊之相同事件類型監聽器將不會被呼叫,而事件也不會繼續捕捉或冒泡傳遞。
- {{domxref("Event.stopPropagation()")}}
- 阻止事件物件繼續捕捉或冒泡傳遞。
-
-
-已廢棄方法
-
-
- {{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
- 非標準方法。回傳 defaultPrevented
屬性值。請直接改用 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性。
- {{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Deprecated_Inline}}
- 已廢棄方法。阻止事件繼續冒泡傳遞。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
- {{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Deprecated_Inline}}
- 已廢棄方法。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
-
-
-規範
+{{APIRef("DOM")}}
+
+**`Event`** 介面表示了一個在 DOM 物件上所發生的事件。
+
+一個事件可以是由使用者的操作行為所產生(如:點擊滑鼠按鈕或敲打鍵盤),或是來自 API 因處理非同步任務所產生。事件也可以為程式所觸發,例如呼叫元素的 [`HTMLElement.click()`](/zh-TW/docs/Web/API/HTMLElement/click) 方法,或是自行定義事件並使用 [`EventTarget.dispatchEvent()`](/zh-TW/docs/Web/API/EventTarget/dispatchEvent) 發送至特定的目標。
+
+事件有多種不同的類型,部分事件是使用基於 `Event` 的子介面。`Event` 本身包含了所有事件共同的屬性及方法。
+
+許多 DOM 元素可被設定接受(accept,或稱為 listen "監聽")這些事件,並在發生時執行處理(process、handle)事件的程式碼。事件處理器(Event-handlers)通常會使用 `EventTarget.addEventListener()` 來被連結(connected,或稱為 attached "附加")至各個 [HTML 元素](/zh-TW/docs/Web/HTML/Element)(例如 \、\、\
、\
等),且此方式一般也是用來取代舊的 HTML [事件處理器屬性(attributes)](/zh-TW/docs/HTML/Global_attributes)。此外,在需要時也可以使用 [`removeEventListener()`](/zh-TW/docs/Web/API/EventTarget/removeEventListener) 來中斷事件處理器與元素的連結。請留意一個元素可以擁有多個事件處理器(即使是處理同一種事件的不同處理器),特別是那些被切分開來彼此獨立且有不同目標的程式模組(舉例來說,廣告及統計模組可以同時監控網頁中的影片觀看資訊)。
+
+When there are many nested elements, each with its own handler(s), event processing can become very complicated -- especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the [Event bubbling and capture](/zh-TW/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) settings of each handler triggered.
+
+## 基於 `Event` 的子介面
+
+Below is a list of interfaces which are based on the main `Event` interface, with links to their respective documentation in the MDN API reference. Note that all event interfaces have names which end in "Event".
+
+- {{domxref("AnimationEvent")}}
+- {{domxref("AudioProcessingEvent")}}
+- {{domxref("BeforeInputEvent")}}
+- {{domxref("BeforeUnloadEvent")}}
+- {{domxref("BlobEvent")}}
+- {{domxref("ClipboardEvent")}}
+- {{domxref("CloseEvent")}}
+- {{domxref("CompositionEvent")}}
+- {{domxref("CSSFontFaceLoadEvent")}}
+- {{domxref("CustomEvent")}}
+- {{domxref("DeviceLightEvent")}}
+- {{domxref("DeviceMotionEvent")}}
+- {{domxref("DeviceOrientationEvent")}}
+- {{domxref("DeviceProximityEvent")}}
+- {{domxref("DOMTransactionEvent")}}
+- {{domxref("DragEvent")}}
+- {{domxref("EditingBeforeInputEvent")}}
+- {{domxref("ErrorEvent")}}
+- {{domxref("FetchEvent")}}
+- {{domxref("FocusEvent")}}
+- {{domxref("GamepadEvent")}}
+- {{domxref("HashChangeEvent")}}
+- {{domxref("IDBVersionChangeEvent")}}
+- {{domxref("InputEvent")}}
+- {{domxref("KeyboardEvent")}}
+- {{domxref("MediaStreamEvent")}}
+- {{domxref("MessageEvent")}}
+- {{domxref("MouseEvent")}}
+- {{domxref("MutationEvent")}}
+- {{domxref("OfflineAudioCompletionEvent")}}
+- {{domxref("OverconstrainedError")}}
+- {{domxref("PageTransitionEvent")}}
+- {{domxref("PaymentRequestUpdateEvent")}}
+- {{domxref("PointerEvent")}}
+- {{domxref("PopStateEvent")}}
+- {{domxref("ProgressEvent")}}
+- {{domxref("RelatedEvent")}}
+- {{domxref("RTCDataChannelEvent")}}
+- {{domxref("RTCIdentityErrorEvent")}}
+- {{domxref("RTCIdentityEvent")}}
+- {{domxref("RTCPeerConnectionIceEvent")}}
+- {{domxref("SensorEvent")}}
+- {{domxref("StorageEvent")}}
+- {{domxref("SVGEvent")}}
+- {{domxref("SVGZoomEvent")}}
+- {{domxref("TimeEvent")}}
+- {{domxref("TouchEvent")}}
+- {{domxref("TrackEvent")}}
+- {{domxref("TransitionEvent")}}
+- {{domxref("UIEvent")}}
+- {{domxref("UserProximityEvent")}}
+- {{domxref("WebGLContextEvent")}}
+- {{domxref("WheelEvent")}}
+
+## 建構式
+
+- {{domxref("Event.Event", "Event()")}}
+ - : 建立一個 `Event` 物件。
+
+## 屬性
+
+- {{domxref("Event.bubbles")}} {{readonlyinline}}
+ - : 布林值,表示事件是否會向上冒泡傳遞。
+- {{domxref("Event.cancelBubble")}}
+ - : 由於歷史性因素,此屬性的效果等同於 {{domxref("Event.stopPropagation()", "stopPropagation()")}} 方法。若在事件處理器回傳前設定此值為 `true`,可阻止事件繼續向上冒泡傳遞。
+- {{domxref("Event.cancelable")}} {{readonlyinline}}
+ - : 布林值,表示事件是否能被取消。
+- {{domxref("Event.composed")}} {{ReadOnlyInline}}
+ - : A Boolean value indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.
+- {{domxref("Event.currentTarget")}} {{readonlyinline}}
+ - : 指向目前處理事件之監聽器所屬的 DOM 物件。
+- {{domxref("Event.deepPath")}} {{non-standard_inline}}
+ - : An {{jsxref("Array")}} of DOM {{domxref("Node")}}s through which the event has bubbled.
+- {{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+ - : 布林值,表示事件的預設行為是否被 {{domxref("event.preventDefault()", "preventDefault()")}} 方法所取消。
+- {{domxref("Event.eventPhase")}} {{readonlyinline}}
+ - : 表示事件目前的傳遞階段。
+- {{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+ - : 事件的明確原定目標(Mozilla 專屬)。
+- {{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+ - : 事件重新導向前的原定目標(Mozilla 專屬)。
+- {{domxref("Event.returnValue")}}
+ - : 非標準屬性。用以替代 {{domxref("Event.preventDefault()", "preventDefault()")}} 方法與 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性(舊版 Internet Explorer 專屬)。
+- {{domxref("Event.scoped")}} {{readonlyinline}} {{Deprecated_Inline}}
+ - : A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
+- {{domxref("Event.srcElement")}} {{non-standard_inline}}
+ - : 非標準屬性。為 {{domxref("Event.target", "target")}} 屬性的別名(舊版 Internet Explorer 專屬)。
+- {{domxref("Event.target")}} {{readonlyinline}}
+ - : 指向最初觸發事件的 DOM 物件。
+- {{domxref("Event.timeStamp")}} {{readonlyinline}}
+ - : 事件發生(事件物件建立)至今的時間。
+- {{domxref("Event.type")}} {{readonlyinline}}
+ - : 事件類型(不區分大小寫)。
+- {{domxref("Event.isTrusted")}} {{readonlyinline}}
+ - : 表示事件物件是否為瀏覽器建立(比如在用戶點擊之後),或由程式碼所建立(使用建立事件的方法,如 {{domxref("Event.initEvent()", "initEvent()")}})。
+
+### Obsolete properties
+
+- {{domxref("Event.scoped")}} {{readonlyinline}} {{Deprecated_Inline}}
+ - : A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
+
+## 方法
+
+- {{domxref("Event.createEvent()")}} {{deprecated_inline}}
+ - : Creates a new event, which must then be initialized by calling its `initEvent()` method.
+- {{domxref("Event.composedPath()")}}
+ - : Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its {{domxref("ShadowRoot.mode")}} closed.
+- {{domxref("Event.initEvent()")}} {{deprecated_inline}}
+ - : 初始化已經建立的事件。若該事件已經被處理過,這方法就不會執行任何東西。
+- {{domxref("Event.preventDefault()")}}
+ - : 取消該事件(如果該事件的 {{domxref("Event.cancelable", "cancelable")}} 屬性為 `true`)。
+- {{domxref("Event.stopImmediatePropagation()")}}
+ - : 一旦事件物件呼叫此方法,目前元素中尚未執行的已註冊之相同事件類型監聽器將不會被呼叫,而事件也不會繼續捕捉或冒泡傳遞。
+- {{domxref("Event.stopPropagation()")}}
+ - : 阻止事件物件繼續捕捉或冒泡傳遞。
+
+### 已廢棄方法
+
+- {{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+ - : 非標準方法。回傳 `defaultPrevented` 屬性值。請直接改用 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性。
+- {{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : 已廢棄方法。阻止事件繼續冒泡傳遞。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
+- {{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : 已廢棄方法。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
+{{Compat("api.Event")}}
+## 參見
-{{Compat("api.Event")}}
+- 可用的事件類型:[Event reference](/zh-TW/docs/Web/Reference/Events)
+- [各種 Event Targets 的比較](/zh-TW/docs/Web/API/Event/Comparison_of_Event_Targets) (target vs currentTarget vs relatedTarget vs originalTarget)
+- [建立和觸發事件](/zh-TW/docs/Web/Guide/Events/Creating_and_triggering_events)
+- 給 Firefox 插件開發者:
-參見
-
-
+ - [Listening to events in Firefox extensions](/zh-TW/docs/Listening_to_events_in_Firefox_extensions)
+ - [Listening to events on all tabs](/zh-TW/docs/Listening_to_events_on_all_tabs)
diff --git a/files/zh-tw/web/api/event/preventdefault/index.md b/files/zh-tw/web/api/event/preventdefault/index.md
index 9acd0fd0205664..21948cf36d4f11 100644
--- a/files/zh-tw/web/api/event/preventdefault/index.md
+++ b/files/zh-tw/web/api/event/preventdefault/index.md
@@ -3,57 +3,60 @@ title: Event.preventDefault()
slug: Web/API/Event/preventDefault
translation_of: Web/API/Event/preventDefault
---
-{{ ApiRef("DOM") }}
+{{ ApiRef("DOM") }}
-
+## 概要
-概要
+如果事件可以被取消,就取消事件(即取消事件的預設行為)。但不會影響事件的傳遞,事件仍會繼續傳遞。
-如果事件可以被取消,就取消事件(即取消事件的預設行為)。但不會影響事件的傳遞,事件仍會繼續傳遞。
+## 語法
-語法
+```js
+event.preventDefault();
+```
-event .preventDefault();
+## 範例
-範例
+Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening:
-Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening:
+```html
+
+
+
+preventDefault example
+
-<!DOCTYPE html>
-<html>
-<head>
-<title>preventDefault example</title>
-</head>
-
-<body>
- <p>Please click on the checkbox control.</p>
- <form>
- <label for="id-checkbox">Checkbox</label>
- <input type="checkbox" id="id-checkbox"/>
- </form>
- <script>
+
+ Please click on the checkbox control.
+
+ Checkbox
+
+
+
+
+
+```
-You can see preventDefault
in action here .
+You can see `preventDefault` in action [here](/samples/domref/dispatchEvent.html).
-The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault().
+The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault().
-
-
<!DOCTYPE html>
-<html>
-<head>
-<title>preventDefault example</title>
+```html hidden
+
+
+
+preventDefault example
-<script>
-
+
+
+
+
Please enter your name using lowercase letters only.
+
+
+
+
+
+```
-
Here is the result of the preceding code:
+Here is the result of the preceding code:
-
{{ EmbedLiveSample('preventDefault_invalid_text', '', '', '') }}
+{{ EmbedLiveSample('preventDefault_invalid_text', '', '', '') }}
-
備註
+## 備註
-
Calling preventDefault
during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
+Calling `preventDefault` during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
-
-
Note: As of {{Gecko("6.0")}}, calling preventDefault()
causes the {{ domxref("event.defaultPrevented") }} property's value to become true
.
-
+> **備註:** As of {{Gecko("6.0")}}, calling `preventDefault()` causes the {{ domxref("event.defaultPrevented") }} property's value to become `true`.
-
你可以查看 {{domxref("Event.cancelable")}} 屬性來檢查事件是否能夠被取消。對一個不能被取消的事件呼叫 preventDefault()
方法是沒有任何效果的。
+你可以查看 {{domxref("Event.cancelable")}} 屬性來檢查事件是否能夠被取消。對一個不能被取消的事件呼叫 `preventDefault()` 方法是沒有任何效果的。
-
preventDefault()
方法不會停止事件傳遞。若要停止事件繼續傳遞,可以使用 {{domxref("Event.stopPropagation()")}} 方法。
+`preventDefault()` 方法不會停止事件傳遞。若要停止事件繼續傳遞,可以使用 {{domxref("Event.stopPropagation()")}} 方法。
-
規範
+## 規範
{{Specifications}}
diff --git a/files/zh-tw/web/api/eventtarget/addeventlistener/index.md b/files/zh-tw/web/api/eventtarget/addeventlistener/index.md
index acf68c27dfd0e6..13723b4ca7a74c 100644
--- a/files/zh-tw/web/api/eventtarget/addeventlistener/index.md
+++ b/files/zh-tw/web/api/eventtarget/addeventlistener/index.md
@@ -8,36 +8,35 @@ tags:
translation_of: Web/API/EventListener
original_slug: Web/API/EventListener
---
-
{{APIRef("DOM Events")}}
+{{APIRef("DOM Events")}}
-
EventListener
介面表示一個可以處理由 {{domxref("EventTarget")}} 物件分派事件的物件。
+**`EventListener`** 介面表示一個可以處理由 {{domxref("EventTarget")}} 物件分派事件的物件。
-
-
注意: 基於相容舊版內容的需要, EventListener
可以接受一個函式及一個帶有 handleEvent()
屬性函式的物件。相關的範例 顯示在下方。
-
+> **備註:** 基於相容舊版內容的需要, `EventListener` 可以接受一個函式及一個帶有 `handleEvent()` 屬性函式的物件。相關的[範例](#Example)顯示在下方。
-
屬性
+## 屬性
-
這個介面並不實作且不繼承任何屬性。
+_這個介面並不實作且不繼承任何屬性。_
-
方法
+## 方法
-
這個介面不繼承任何方法。
+_這個介面不繼承任何方法。_
-
- {{domxref("EventListener.handleEvent()")}}
- 一個可以在指定類型事件發生時被呼叫的函數。
-
+- {{domxref("EventListener.handleEvent()")}}
+ - : 一個可以在指定類型事件發生時被呼叫的函數。
-
範例
+## 範例
-
HTML
+### HTML
-
<button id="btn">Click here!</button>
+```html
+
Click here!
+```
-
JavaScript
+### JavaScript
-
const buttonElement = document.getElementById('btn');
+```js
+const buttonElement = document.getElementById('btn');
// 透過提供回呼函數的方式對「click」事件新增處理器。
// 當元素被點選後會出現「Element clicked!」的彈出訊息。
@@ -51,22 +50,20 @@ buttonElement.addEventListener('click', {
alert('Element clicked through handleEvent property!');
}
});
-
+```
-
結果
+### 結果
-
{{EmbedLiveSample('Example')}}
+{{EmbedLiveSample('Example')}}
-
檢閱相關:
+### 檢閱相關:
-
+- [addEventListener](/zh-TW/docs/Web/API/EventTarget/addEventListener)
-
規格
+## 規格
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
-
{{Compat}}
+{{Compat}}
diff --git a/files/zh-tw/web/api/eventtarget/index.md b/files/zh-tw/web/api/eventtarget/index.md
index a5b88f2d06a667..d3709bd8614ea9 100644
--- a/files/zh-tw/web/api/eventtarget/index.md
+++ b/files/zh-tw/web/api/eventtarget/index.md
@@ -32,7 +32,7 @@ translation_of: Web/API/EventTarget
### Mozilla chrome code 的額外方法
-Mozilla extensions for use by JS-implemented event targets to implement on\* properties. See also [WebIDL bindings](/docs/Mozilla/WebIDL_bindings).
+Mozilla extensions for use by JS-implemented event targets to implement on properties. See also [WebIDL bindings](/docs/Mozilla/WebIDL_bindings).
- void **setEventHandler**(DOMString type, EventHandler handler) {{non-standard_inline}}
- EventHandler **getEventHandler**(DOMString type) {{non-standard_inline}}
diff --git a/files/zh-tw/web/api/eventtarget/removeeventlistener/index.md b/files/zh-tw/web/api/eventtarget/removeeventlistener/index.md
index 600c4067168a6f..18696ed0f311b9 100644
--- a/files/zh-tw/web/api/eventtarget/removeeventlistener/index.md
+++ b/files/zh-tw/web/api/eventtarget/removeeventlistener/index.md
@@ -3,52 +3,48 @@ title: EventTarget.removeEventListener()
slug: Web/API/EventTarget/removeEventListener
translation_of: Web/API/EventTarget/removeEventListener
---
-
{{APIRef("DOM Events")}}
+{{APIRef("DOM Events")}}
-
EventTarget.removeEventListener()
方法可以移除先前由 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 所註冊的事件監聽器。
+**`EventTarget.removeEventListener()`** 方法可以移除先前由 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 所註冊的事件監聽器。
-
語法
+## 語法
-
target .removeEventListener(type , listener [, options ]);
-
target .removeEventListener(type , listener [, useCapture ]);
-
+```js
+target.removeEventListener(type, listener[, options]);
+target.removeEventListener(type, listener[, useCapture]);
+```
-
參數
+### 參數
-
- type
- A string representing the event type to remove.
- listener
- The {{domxref("EventListener")}} function to remove from the event target.
- options {{optional_inline}}
- An options object that specifies characteristics about the event listener. The available options are:
-
- capture
: A {{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered listener
before being dispatched to any EventTarget
beneath it in the DOM tree.
- passive
: A {{jsxref("Boolean")}} indicating that the listener
will never call preventDefault()
. If it does, the user agent should ignore it and generate a console warning.
- {{non-standard_inline}} mozSystemGroup
: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group.
-
-
- useCapture
{{optional_inline}}
- Specifies whether the {{domxref("EventListener")}} to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of false
is assumed. If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
-
+- `type`
+ - : A string representing the event type to remove.
+- `listener`
+ - : The {{domxref("EventListener")}} function to remove from the event target.
+- options {{optional_inline}}
+ - : An options object that specifies characteristics about the event listener. The available options are: `capture`: A {{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered `listener` before being dispatched to any `EventTarget` beneath it in the DOM tree.
+ - `passive`: A {{jsxref("Boolean")}} indicating that the `listener` will never call `preventDefault()`. If it does, the user agent should ignore it and generate a console warning.
+ - {{non-standard_inline}}` mozSystemGroup`: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group.
+- `useCapture` {{optional_inline}}
+ - : Specifies whether the {{domxref("EventListener")}} to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of `false` is assumed. If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
-
Note: useCapture
was required in most major browsers' early versions. If broad compatibility is desired, you should always provide the useCapture
parameter.
+> **備註:** `useCapture` was required in most major browsers' early versions. If broad compatibility is desired, you should always provide the `useCapture` parameter.
-
回傳值
+### 回傳值
-
無。
+無。
-
備註
+## 備註
-
If an {{domxref("EventListener")}} is removed from an {{domxref("EventTarget")}} while it is processing an event, it will not be triggered by the current actions. An {{domxref("EventListener")}} will not be invoked for the event it was registered for after being removed, however it can be reattached.
+If an {{domxref("EventListener")}} is removed from an {{domxref("EventTarget")}} while it is processing an event, it will not be triggered by the current actions. An {{domxref("EventListener")}} will not be invoked for the event it was registered for after being removed, however it can be reattached.
-
Calling removeEventListener()
with arguments that do not identify any currently registered {{domxref("EventListener")}} on the EventTarget
has no effect.
+Calling `removeEventListener()` with arguments that do not identify any currently registered {{domxref("EventListener")}} on the `EventTarget` has no effect.
-
範例
+## 範例
-
This example shows how to add a click
-based event listener and remove a mouseover
-based event listener.
+This example shows how to add a `click`-based event listener and remove a `mouseover`-based event listener.
-
var body =
+```js
+var body =
document.querySelector('body'),
clickTarget =
document.getElementById('click-target'),
@@ -81,27 +77,28 @@ mouseOverTarget.addEventListener('mouseover', function () {
false
);
});
-
+```
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.EventTarget.removeEventListener")}}
-
Polyfill to support older browsers
+## Polyfill to support older browsers
-
addEventListener()
and removeEventListener()
are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing the use of addEventListener()
and removeEventListener()
in implementations that do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.
+`addEventListener()` and `removeEventListener()` are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing the use of `addEventListener()` and `removeEventListener()` in implementations that do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.
-
if (!Element.prototype.addEventListener) {
+```js
+if (!Element.prototype.addEventListener) {
var oListeners = {};
function runListeners(oEvent) {
if (!oEvent) { oEvent = window.event; }
- for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
+ for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
if (oEvtListeners.aEls[iElId] === this) {
- for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
+ for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
break;
}
}
@@ -109,7 +106,7 @@ mouseOverTarget.addEventListener('mouseover', function () {
Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
if (oListeners.hasOwnProperty(sEventType)) {
var oEvtListeners = oListeners[sEventType];
- for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+ for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
}
if (nElIdx === -1) {
@@ -122,7 +119,7 @@ mouseOverTarget.addEventListener('mouseover', function () {
aElListeners.splice(0);
this["on" + sEventType] = runListeners;
}
- for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
+ for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
if (aElListeners[iLstId] === fListener) { return; }
}
aElListeners.push(fListener);
@@ -135,20 +132,18 @@ mouseOverTarget.addEventListener('mouseover', function () {
Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
if (!oListeners.hasOwnProperty(sEventType)) { return; }
var oEvtListeners = oListeners[sEventType];
- for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+ for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
}
if (nElIdx === -1) { return; }
- for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
+ for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
}
};
}
-
+```
-
參見
+## 參見
-
- {{domxref("EventTarget.addEventListener()")}}.
- {{non-standard_inline}}{{domxref("EventTarget.detachEvent()")}}.
-
+- {{domxref("EventTarget.addEventListener()")}}.
+- {{non-standard_inline}}{{domxref("EventTarget.detachEvent()")}}.
diff --git a/files/zh-tw/web/api/fetch_api/index.md b/files/zh-tw/web/api/fetch_api/index.md
index 7206fcdcf88425..d1307ffcdb8fc3 100644
--- a/files/zh-tw/web/api/fetch_api/index.md
+++ b/files/zh-tw/web/api/fetch_api/index.md
@@ -3,67 +3,57 @@ title: Fetch API
slug: Web/API/Fetch_API
translation_of: Web/API/Fetch_API
---
-
{{DefaultAPISidebar("Fetch API")}}
+{{DefaultAPISidebar("Fetch API")}}Fetch API 提供了一個能獲取包含跨網路資源在的資源介面。它有點像我們所熟悉的 {{domxref("XMLHttpRequest")}} ,但這個新的 API 提供了更強更彈性的功能。
-
Fetch API 提供了一個能獲取包含跨網路資源在的資源介面。它有點像我們所熟悉的 {{domxref("XMLHttpRequest")}} ,但這個新的 API 提供了更強更彈性的功能。
+## 概念與應用
-
概念與應用
+Fetch 提供了 {{domxref("Request")}} 與 {{domxref("Response")}} 物件,還有其他牽涉網路請求的通用定義。這能讓他們在需要的時候被使用到,不管是 service worker、Cache API、還是其他處理或更動請求回應的相類事物、或是任何需要產生有序化產生回應的用例(use case)。
-
Fetch 提供了 {{domxref("Request")}} 與 {{domxref("Response")}} 物件,還有其他牽涉網路請求的通用定義。這能讓他們在需要的時候被使用到,不管是 service worker、Cache API、還是其他處理或更動請求回應的相類事物、或是任何需要產生有序化產生回應的用例(use case)。
+它也提供了諸如 CORS 與 HTTP origin 標頭語意的分散定義,能取代分散的定義。
-
它也提供了諸如 CORS 與 HTTP origin 標頭語意的分散定義,能取代分散的定義。
+要發動請求並取得資源的話,請使用 {{domxref("GlobalFetch.fetch")}} 方法。他實作了數種介面,並指定了 {{domxref("Window")}} 與 {{domxref("WorkerGlobalScope")}},使它可以在任何想獲取資源的環境中使用。
-
要發動請求並取得資源的話,請使用 {{domxref("GlobalFetch.fetch")}} 方法。他實作了數種介面,並指定了 {{domxref("Window")}} 與 {{domxref("WorkerGlobalScope")}},使它可以在任何想獲取資源的環境中使用。
+`fetch()` 方法有一個強制性的參數,就是要取得資源的網址。該方法會回傳一個不論請求成敗,都會 resolve 的 promise {{domxref("Response","回應")}}。你也能選擇性地使用第二個稱為 `init` 的物件參數(請參見 {{domxref("Request")}})。
-
fetch()
方法有一個強制性的參數,就是要取得資源的網址。該方法會回傳一個不論請求成敗,都會 resolve 的 promise {{domxref("Response","回應")}}。你也能選擇性地使用第二個稱為 init
的物件參數(請參見 {{domxref("Request")}})。
+當 {{domxref("Response")}} 檢索後,在請求體裡面會定義一些請求體為何,還有要如何處理的方法(請參見 {{domxref("Body")}})。
-
當 {{domxref("Response")}} 檢索後,在請求體裡面會定義一些請求體為何,還有要如何處理的方法(請參見 {{domxref("Body")}})。
+你也可以直接用 {{domxref("Request.Request","Request()")}} 與 {{domxref("Response.Response","Response()")}} 建構子來建立請求與回應,不過你不太可能直接使用他,反而更可能是以其他 API 行動的結果為形式存在。(例如來自 service worker 的 {{domxref("FetchEvent.respondWith")}})
-
你也可以直接用 {{domxref("Request.Request","Request()")}} 與 {{domxref("Response.Response","Response()")}} 建構子來建立請求與回應,不過你不太可能直接使用他,反而更可能是以其他 API 行動的結果為形式存在。(例如來自 service worker 的 {{domxref("FetchEvent.respondWith")}})
+> **備註:** 你可以在[使用 Fetch](/zh-TW/docs/Web/API/Fetch_API/Using_Fetch)深入理解 Fetch,並在[Fetch 的基本概念](/zh-TW/docs/Web/API/Fetch_API/Basic_concepts)文章內理解概念。
-
+### 中斷一次 Fetch
-
中斷一次 Fetch
+各家瀏覽器已經開始加入 {{DOMxRef("AbortController")}} 與 {{DOMxRef("AbortSignal")}} 介面(也就是 Abort API)的實驗性支援,讓 Fetch 和 XHR 這類的操作在完成前可以被中斷。詳情請參閱相關介面的文件。
-
各家瀏覽器已經開始加入 {{DOMxRef("AbortController")}} 與 {{DOMxRef("AbortSignal")}} 介面(也就是 Abort API)的實驗性支援,讓 Fetch 和 XHR 這類的操作在完成前可以被中斷。詳情請參閱相關介面的文件。
+## Fetch 介面
-
Fetch 介面
+- {{DOMxRef("fetch()")}}
+ - : 用於取得資源的 `fetch()` 方法。
+- {{domxref("Headers")}}
+ - : 代表請求/回應標頭,讓你能 query 並針對結果不同,採取不同行動。
+- {{domxref("Request")}}
+ - : 代表資源請求。
+- {{domxref("Response")}}
+ - : 代表資源請求的回應。
-
- {{DOMxRef("fetch()")}}
- 用於取得資源的 fetch()
方法。
- {{domxref("Headers")}}
- 代表請求/回應標頭,讓你能 query 並針對結果不同,採取不同行動。
- {{domxref("Request")}}
- 代表資源請求。
- {{domxref("Response")}}
- 代表資源請求的回應。
-
+## Fetch mixin
-
Fetch mixin
+- {{domxref("Body")}}
+ - : 提供請求/回應訊息體的相關方法,能宣告內容的類別為何,以及該如何處理。
-
- {{domxref("Body")}}
- 提供請求/回應訊息體的相關方法,能宣告內容的類別為何,以及該如何處理。
-
-
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.fetch")}}
-
參見
+## 參見
-
+- [使用 Fetch](/zh-TW/docs/Web/API/Fetch_API/Using_Fetch)
+- [ServiceWorker API](/zh-TW/docs/Web/API/ServiceWorker_API)
+- [HTTP access control (CORS)](/zh-TW/docs/Web/HTTP/Access_control_CORS)
+- [HTTP](/zh-TW/docs/Web/HTTP)
+- [Fetch polyfill](https://github.com/github/fetch)
+- [Fetch 基本概念](/zh-TW/docs/Web/API/Fetch_API/Basic_concepts)
diff --git a/files/zh-tw/web/api/fetch_api/using_fetch/index.md b/files/zh-tw/web/api/fetch_api/using_fetch/index.md
index 5adcb6963524dd..b75902d873ac5e 100644
--- a/files/zh-tw/web/api/fetch_api/using_fetch/index.md
+++ b/files/zh-tw/web/api/fetch_api/using_fetch/index.md
@@ -9,59 +9,54 @@ tags:
- request
translation_of: Web/API/Fetch_API/Using_Fetch
---
-
{{DefaultAPISidebar("Fetch API")}}
+{{DefaultAPISidebar("Fetch API")}}
-
-
Fetch API 提供了一種 JavaScript Interface 來操作 HTTP pipeline,比方 request 和 response。同時它也提供了 global 的 {{domxref("GlobalFetch.fetch","fetch()")}} method,使得在網路上非同步地 fetch resources 這件事變得簡單易懂。
-
+[Fetch API](/zh-TW/docs/Web/API/Fetch_API) 提供了一種 JavaScript Interface 來操作 HTTP pipeline,比方 request 和 response。同時它也提供了 global 的 {{domxref("GlobalFetch.fetch","fetch()")}} method,使得在網路上非同步地 fetch resources 這件事變得簡單易懂。
-
同樣的功能,以前都是使用 {{domxref("XMLHttpRequest")}},而 Fetch 作為其替代方案,能更方便地整合在如 {{domxref("ServiceWorker_API", "Service Workers")}} 等相關技術上。此外,Fetch 具備額外的 logical palce,能拿來定義其他和 HTTP 有關的東西,像是 CORS 和 HTTP extensions。
+同樣的功能,以前都是使用 {{domxref("XMLHttpRequest")}},而 Fetch 作為其替代方案,能更方便地整合在如 {{domxref("ServiceWorker_API", "Service Workers")}} 等相關技術上。此外,Fetch 具備額外的 logical palce,能拿來定義其他和 HTTP 有關的東西,像是 CORS 和 HTTP extensions。
-
fetch
和 jQuery.ajax()
有三個主要的差異:
+`fetch` 和 `jQuery.ajax()` 有三個主要的差異:
-
- fetch()
回傳的 promise 不會 reject HTTP 的 error status ,就算是 HTTP 404 或 500 也一樣。相反地,它會正常地 resolve,並把 ok
status 設為 false。會讓它發生 reject 的只有網路錯誤或其他會中斷 request 的情況。
- fetch
可以接收跨站的 cookies ,你可以用 Fetch 來建立跨站的 session。
- fetch
不會傳送 cookies ,除非你有設定 credentials 的 init option 。 (Since Aug 25, 2017 . The spec changed the default credentials policy to same-origin
. Firefox changed since 61.0b13.)
-
+- `fetch()` 回傳的 promise **不會 reject HTTP 的 error status**,就算是 HTTP 404 或 500 也一樣。相反地,它會正常地 resolve,並把 `ok` status 設為 false。會讓它發生 reject 的只有網路錯誤或其他會中斷 request 的情況。
+- `fetch` **可以接收跨站的 cookies**,你可以用 Fetch 來建立跨站的 session。
+- `fetch` **不會傳送 cookies**,除非你有設定 credentials 的 [init option](/zh-TW/docs/Web/API/fetch#Parameters)。 (Since [Aug 25, 2017](https://github.com/whatwg/fetch/pull/585). The spec changed the default credentials policy to `same-origin`. Firefox changed since 61.0b13.)
-
使用 Fetch 發送請求 ( request )
+## 使用 Fetch 發送請求 ( request )
-
用法簡單,如下:
+用法簡單,如下:
-
fetch('http://example.com/movies.json')
+```js
+fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
+```
-
+這裡要使用 fetch 透過網路取得 json 然後印出在 console,最簡單的方式只需要一個參數就是資料的 URI,fetch 會回傳一個包含 response 的 promise 。
-
這裡要使用 fetch 透過網路取得 json 然後印出在 console,最簡單的方式只需要一個參數就是資料的 URI,fetch 會回傳一個包含 response 的 promise 。
+這個範例使用的 url 只是示意用。
-
這個範例使用的 url 只是示意用。
+回傳的 response 需要透過 {{domxref("Body.json","json()")}} (在 {{domxref("Body")}} 可以找到定義, Body 是用 {{domxref("Request")}} 和 {{domxref("Response")}} 實作出來的物件.)
-
回傳的 response 需要透過 {{domxref("Body.json","json()")}} (在 {{domxref("Body")}} 可以找到定義, Body 是用 {{domxref("Request")}} 和 {{domxref("Response")}} 實作出來的物件.)
+> **備註:** 其實 Body 還提供了其他類似的功能可以將內容輸成其他類型格式,詳見[Body](#body)
-
-
備註 : 其實 Body 還提供了其他類似的功能可以將內容輸成其他類型格式,詳見Body
-
+Fetch 請求的安全性 [Content Security Policy](/zh-TW/docs/Security/CSP/CSP_policy_directives)(內容安全策略) 是由 header 中的 `connect-src` directive 所設定 ,並非其他 directive ( 比如:img-src、default-src 等)。
-
Fetch 請求的安全性 Content Security Policy (內容安全策略) 是由 header 中的 connect-src
directive 所設定 ,並非其他 directive ( 比如:img-src、default-src 等)。
+### Request 可用的設定值
-
Request 可用的設定值
+`fetch()` 第二個參數是選用的,可以傳送一個 `init` Object 來設定 request。
-
fetch()
第二個參數是選用的,可以傳送一個 init
Object 來設定 request。
+更多可以用的設定值詳見 {{domxref("GlobalFetch.fetch","fetch()")}}
-
更多可以用的設定值詳見 {{domxref("GlobalFetch.fetch","fetch()")}}
-
-
// 來發個 POST Request:
+```js
+// 來發個 POST Request:
postData('http://example.com/answer', {answer: 42})
- .then(data => console.log(data)) // JSON from `response.json()` call
- .catch(error => console.error(error))
+ .then(data => console.log(data)) // JSON from `response.json()` call
+ .catch(error => console.error(error))
function postData(url, data) {
// Default options are marked with *
@@ -78,37 +73,44 @@ function postData(url, data) {
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
- .then(response => response.json()) // 輸出成 json
+ .then(response => response.json()) // 輸出成 json
}
-
+```
-
包含憑證(Credentials) 的 Request 用法
+### 包含憑證(Credentials) 的 Request 用法
-
要讓瀏覽器將 credentials 跟著 request 一起送出, 方式就是在 init
object 加上 credentials: 'include'
+要讓瀏覽器將 credentials 跟著 request 一起送出, 方式就是在 `init` object 加上 `credentials: 'include'`
-
fetch('https://example.com', {
+```js
+fetch('https://example.com', {
credentials: 'include'
-})
+})
+```
-
如果只想要把 credentials 發送給同源的 URL ,加上credentials: 'same-origin'
。
+如果只想要把 credentials 發送給同源的 URL ,加上`credentials: 'same-origin'`。
-
// The calling script is on the origin 'https://example.com'
+```js
+// The calling script is on the origin 'https://example.com'
fetch('https://example.com', {
credentials: 'same-origin'
-})
+})
+```
-
或要確保瀏覽器不會帶著 credentials 請求,可以用 credentials: 'omit'
。
+或要確保瀏覽器不會帶著 credentials 請求,可以用 `credentials: 'omit'` 。
-
fetch('https://example.com', {
+```js
+fetch('https://example.com', {
credentials: 'omit'
-})
+})
+```
-
上傳JSON資料
+### 上傳 JSON 資料
-
使用 {{domxref("GlobalFetch.fetch","fetch()")}} 來 POST JSON 格式的資料。
+使用 {{domxref("GlobalFetch.fetch","fetch()")}} 來 POST JSON 格式的資料。
-
var url = 'https://example.com/profile';
+```js
+var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
@@ -117,16 +119,17 @@ fetch(url, {
headers: new Headers({
'Content-Type': 'application/json'
})
-}).then(res => res.json())
-.catch(error => console.error('Error:', error))
-.then(response => console.log('Success:', response));
-
+}).then(res => res.json())
+.catch(error => console.error('Error:', error))
+.then(response => console.log('Success:', response));
+```
-
上傳檔案
+### 上傳檔案
-
上傳檔案可以透過使用HTML <input type="file" />
input element, {{domxref("FormData.FormData","FormData()")}} 與{{domxref("GlobalFetch.fetch","fetch()")}}.
+上傳檔案可以透過使用 HTML `
` input element, {{domxref("FormData.FormData","FormData()")}} 與{{domxref("GlobalFetch.fetch","fetch()")}}.
-
var formData = new FormData();
+```js
+var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username', 'abc123');
@@ -136,18 +139,19 @@ fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
-.then(response => response.json())
-.catch(error => console.error('Error:', error))
-.then(response => console.log('Success:', response));
-
+.then(response => response.json())
+.catch(error => console.error('Error:', error))
+.then(response => console.log('Success:', response));
+```
-
如何確認fetch是否成功
+### 如何確認 fetch 是否成功
-
當{{domxref("GlobalFetch.fetch","fetch()")}}遇到CORS或server設定錯誤導致network error時, promise會reject並附上{{jsxref("TypeError")}}的回應, 但在權限或類似問題導致404的常見狀況下, 卻不會導致network error.
+當{{domxref("GlobalFetch.fetch","fetch()")}}遇到 CORS 或 server 設定錯誤導致 network error 時, promise 會 reject 並附上{{jsxref("TypeError")}}的回應, 但在權限或類似問題導致 404 的常見狀況下, 卻不會導致 network error.
-
因此, 確認fetch()
是否成功的正確方式, 應包含檢查promise resolved, 以及檢查{{domxref("Response.ok")}}的屬性是否為true. 代碼如下例:
+因此, 確認`fetch()`是否成功的正確方式, 應包含檢查 promise resolved, 以及檢查{{domxref("Response.ok")}}的屬性是否為 true. 代碼如下例:
-
fetch('flowers.jpg').then(function(response) {
+```js
+fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
@@ -157,13 +161,15 @@ fetch('https://example.com/profile/avatar', {
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
-});
+});
+```
-
Supplying your own request object
+### Supplying your own request object
-
Instead of passing a path to the resource you want to request into the fetch()
call, you can create a request object using the {{domxref("Request.Request","Request()")}} constructor, and pass that in as a fetch()
method argument:
+Instead of passing a path to the resource you want to request into the `fetch()` call, you can create a request object using the {{domxref("Request.Request","Request()")}} constructor, and pass that in as a `fetch()` method argument:
-
var myHeaders = new Headers();
+```js
+var myHeaders = new Headers();
var myInit = { method: 'GET',
headers: myHeaders,
@@ -177,39 +183,45 @@ fetch(myRequest).then(function(response) {
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
-});
+});
+```
-
Request()
accepts exactly the same parameters as the fetch()
method. You can even pass in an existing request object to create a copy of it:
+`Request()` accepts exactly the same parameters as the `fetch()` method. You can even pass in an existing request object to create a copy of it:
-
var anotherRequest = new Request(myRequest, myInit);
+```js
+var anotherRequest = new Request(myRequest, myInit);
+```
-
This is pretty useful, as request and response bodies are one use only. Making a copy like this allows you to make use of the request/response again, while varying the init
options if desired. The copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request.
+This is pretty useful, as request and response bodies are one use only. Making a copy like this allows you to make use of the request/response again, while varying the `init` options if desired. The copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request.
-
-
Note : There is also a {{domxref("Request.clone","clone()")}} method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.
-
+> **備註:** There is also a {{domxref("Request.clone","clone()")}} method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.
-
+## Headers
-
The {{domxref("Headers")}} interface allows you to create your own headers object via the {{domxref("Headers.Headers","Headers()")}} constructor. A headers object is a simple multi-map of names to values:
+The {{domxref("Headers")}} interface allows you to create your own headers object via the {{domxref("Headers.Headers","Headers()")}} constructor. A headers object is a simple multi-map of names to values:
-
var content = "Hello World";
+```js
+var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
-myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
+myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
+```
-
The same can be achieved by passing an array of arrays or an object literal to the constructor:
+The same can be achieved by passing an array of arrays or an object literal to the constructor:
-
myHeaders = new Headers({
+```js
+myHeaders = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
-});
+});
+```
-
The contents can be queried and retrieved:
+The contents can be queried and retrieved:
-
console.log(myHeaders.has("Content-Type")); // true
+```js
+console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");
@@ -218,64 +230,64 @@ console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.get("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
myHeaders.delete("X-Custom-Header");
-console.log(myHeaders.get("X-Custom-Header")); // [ ]
+console.log(myHeaders.get("X-Custom-Header")); // [ ]
+```
-
Some of these operations are only useful in {{domxref("ServiceWorker_API","ServiceWorkers")}}, but they provide a much nicer API for manipulating headers.
+Some of these operations are only useful in {{domxref("ServiceWorker_API","ServiceWorkers")}}, but they provide a much nicer API for manipulating headers.
-
All of the Headers methods throw a TypeError
if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError
if there is an immutable guard (see below). Otherwise they fail silently. For example:
+All of the Headers methods throw a `TypeError` if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a `TypeError` if there is an immutable guard (see below). Otherwise they fail silently. For example:
-
var myResponse = Response.error();
+```js
+var myResponse = Response.error();
try {
myResponse.headers.set("Origin", "http://mybank.com");
} catch(e) {
console.log("Cannot pretend to be a bank!");
-}
+}
+```
-
A good use case for headers is checking whether the content type is correct before you process it further. For example:
+A good use case for headers is checking whether the content type is correct before you process it further. For example:
-
fetch(myRequest).then(function(response) {
+```js
+fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
- if(contentType && contentType.includes("application/json")) {
+ if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
- .catch(function(error) { console.log(error); });
+ .catch(function(error) { console.log(error); });
+```
-
Guard
+### Guard
-
Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.
+Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.
-
Possible guard values are:
+Possible guard values are:
-
- none
: default.
- request
: guard for a headers object obtained from a request ({{domxref("Request.headers")}}).
- request-no-cors
: guard for a headers object obtained from a request created with {{domxref("Request.mode")}} no-cors
.
- response
: guard for a Headers obtained from a response ({{domxref("Response.headers")}}).
- immutable
: Mostly used for ServiceWorkers; renders a headers object read-only.
-
+- `none`: default.
+- `request`: guard for a headers object obtained from a request ({{domxref("Request.headers")}}).
+- `request-no-cors`: guard for a headers object obtained from a request created with {{domxref("Request.mode")}} `no-cors`.
+- `response`: guard for a Headers obtained from a response ({{domxref("Response.headers")}}).
+- `immutable`: Mostly used for ServiceWorkers; renders a headers object read-only.
-
-
Note : You may not append or set a request
guarded Headers’ Content-Length
header. Similarly, inserting Set-Cookie
into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.
-
+> **備註:** You may not append or set a `request` guarded Headers’ `Content-Length` header. Similarly, inserting `Set-Cookie` into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.
-
Response objects
+## Response objects
-
As you have seen above, {{domxref("Response")}} instances are returned when fetch()
promises are resolved.
+As you have seen above, {{domxref("Response")}} instances are returned when `fetch()` promises are resolved.
-
The most common response properties you'll use are:
+The most common response properties you'll use are:
-
- {{domxref("Response.status")}} — An integer (default value 200) containing the response status code.
- {{domxref("Response.statusText")}} — A string (default value "OK"), which corresponds to the HTTP status code message.
- {{domxref("Response.ok")}} — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a {{domxref("Boolean")}}.
-
+- {{domxref("Response.status")}} — An integer (default value 200) containing the response status code.
+- {{domxref("Response.statusText")}} — A string (default value "OK"), which corresponds to the HTTP status code message.
+- {{domxref("Response.ok")}} — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a {{domxref("Boolean")}}.
-
They can also be created programmatically via JavaScript, but this is only really useful in {{domxref("ServiceWorker_API", "ServiceWorkers")}}, when you are providing a custom response to a received request using a {{domxref("FetchEvent.respondWith","respondWith()")}} method:
+They can also be created programmatically via JavaScript, but this is only really useful in {{domxref("ServiceWorker_API", "ServiceWorkers")}}, when you are providing a custom response to a received request using a {{domxref("FetchEvent.respondWith","respondWith()")}} method:
-
var myBody = new Blob();
+```js
+var myBody = new Blob();
addEventListener('fetch', function(event) { // ServiceWorker intercepting a fetch
event.respondWith(
@@ -283,80 +295,74 @@ addEventListener('fetch', function(event) { // ServiceWorker intercepting a fetc
headers: { "Content-Type" : "text/plain" }
})
);
-});
+});
+```
-
The {{domxref("Response.Response","Response()")}} constructor takes two optional arguments — a body for the response, and an init object (similar to the one that {{domxref("Request.Request","Request()")}} accepts.)
+The {{domxref("Response.Response","Response()")}} constructor takes two optional arguments — a body for the response, and an init object (similar to the one that {{domxref("Request.Request","Request()")}} accepts.)
-
+> **備註:** The static method {{domxref("Response.error","error()")}} simply returns an error response. Similarly, {{domxref("Response.redirect","redirect()")}} returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.
-
-
Note : The static method {{domxref("Response.error","error()")}} simply returns an error response. Similarly, {{domxref("Response.redirect","redirect()")}} returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.
-
+## Body
-
Body
+Both requests and responses may contain body data. A body is an instance of any of the following types:
-
Both requests and responses may contain body data. A body is an instance of any of the following types:
+- {{domxref("ArrayBuffer")}}
+- {{domxref("ArrayBufferView")}} (Uint8Array and friends)
+- {{domxref("Blob")}}/File
+- string
+- {{domxref("URLSearchParams")}}
+- {{domxref("FormData")}}
-
- {{domxref("ArrayBuffer")}}
- {{domxref("ArrayBufferView")}} (Uint8Array and friends)
- {{domxref("Blob")}}/File
- string
- {{domxref("URLSearchParams")}}
- {{domxref("FormData")}}
-
+The {{domxref("Body")}} mixin defines the following methods to extract a body (implemented by both {{domxref("Request")}} and {{domxref("Response")}}). These all return a promise that is eventually resolved with the actual content.
-
The {{domxref("Body")}} mixin defines the following methods to extract a body (implemented by both {{domxref("Request")}} and {{domxref("Response")}}). These all return a promise that is eventually resolved with the actual content.
+- {{domxref("Body.arrayBuffer","arrayBuffer()")}}
+- {{domxref("Body.blob","blob()")}}
+- {{domxref("Body.json","json()")}}
+- {{domxref("Body.text","text()")}}
+- {{domxref("Body.formData","formData()")}}
-
- {{domxref("Body.arrayBuffer","arrayBuffer()")}}
- {{domxref("Body.blob","blob()")}}
- {{domxref("Body.json","json()")}}
- {{domxref("Body.text","text()")}}
- {{domxref("Body.formData","formData()")}}
-
+This makes usage of non-textual data much easier than it was with XHR.
-
This makes usage of non-textual data much easier than it was with XHR.
+Request bodies can be set by passing body parameters:
-
Request bodies can be set by passing body parameters:
-
-
var form = new FormData(document.getElementById('login-form'));
+```js
+var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
method: "POST",
body: form
-});
+});
+```
-
Both request and response (and by extension the fetch()
function), will try to intelligently determine the content type. A request will also automatically set a Content-Type
header if none is set in the dictionary.
+Both request and response (and by extension the `fetch()` function), will try to intelligently determine the content type. A request will also automatically set a `Content-Type` header if none is set in the dictionary.
-
特性偵測
+## 特性偵測
-
想確認是否支持 Fetch API,可透過檢查 {{domxref("Headers")}}、{{domxref("Request")}}、{{domxref("Response")}} 或 {{domxref("GlobalFetch.fetch","fetch()")}} 是否存在 {{domxref("Window")}} 或 {{domxref("Worker")}} 域中。例如:
+想確認是否支持 Fetch API,可透過檢查 {{domxref("Headers")}}、{{domxref("Request")}}、{{domxref("Response")}} 或 {{domxref("GlobalFetch.fetch","fetch()")}} 是否存在 {{domxref("Window")}} 或 {{domxref("Worker")}} 域中。例如:
-
if (self.fetch) {
+```js
+if (self.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
-}
+}
+```
-
Polyfill
+## Polyfill
-
在不支援 Fetch 的瀏覽器, 可改用 Fetch Polyfill 來重新支持缺少的 fetch 功能。
+在不支援 Fetch 的瀏覽器, 可改用 [Fetch Polyfill](https://github.com/github/fetch) 來重新支持缺少的 fetch 功能。
-
技術指標
+## 技術指標
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
-
{{Compat}}
+{{Compat}}
-
參見
+## 參見
-
+- [ServiceWorker API](/zh-TW/docs/Web/API/ServiceWorker_API)
+- [HTTP access control (CORS)](/zh-TW/docs/Web/HTTP/Access_control_CORS)
+- [HTTP](/zh-TW/docs/Web/HTTP)
+- [Fetch polyfill](https://github.com/github/fetch)
+- [Fetch examples on Github](https://github.com/mdn/fetch-examples/)
diff --git a/files/zh-tw/web/api/file/name/index.md b/files/zh-tw/web/api/file/name/index.md
index ec5acebd1b0a4e..2fd6c25fd413f2 100644
--- a/files/zh-tw/web/api/file/name/index.md
+++ b/files/zh-tw/web/api/file/name/index.md
@@ -4,30 +4,30 @@ slug: Web/API/File/name
translation_of: Web/API/File/fileName
original_slug: Web/API/File/fileName
---
-
{{APIRef("File API")}}{{non-standard_header}}
+{{APIRef("File API")}}{{non-standard_header}}
-
{{deprecated_header(7.0)}}
+{{deprecated_header(7.0)}}
-
總覽
+## 總覽
-
回傳檔案名稱,基於安全因素,檔案路徑不包含這個屬性。
+回傳檔案名稱,基於安全因素,檔案路徑不包含這個屬性。
-
這個檔案是廢棄的,使用 {{domxref("File.name")}} 取代。
+> **備註:** 這個檔案是廢棄的,使用 {{domxref("File.name")}} 取代。
-
語法
+## 語法
-
var name = instanceOfFile.fileName
+```js
+var name = instanceOfFile.fileName
+```
-
數值
+## 數值
-
字串
+字串
-
格式
+## 格式
-
尚無資料
+尚無資料
-
看更多
+## 看更多
-
- {{domxref("File.name")}}
-
+- {{domxref("File.name")}}
diff --git a/files/zh-tw/web/api/file_and_directory_entries_api/index.md b/files/zh-tw/web/api/file_and_directory_entries_api/index.md
index 017434ddd79ddc..7e45ff3ed9b434 100644
--- a/files/zh-tw/web/api/file_and_directory_entries_api/index.md
+++ b/files/zh-tw/web/api/file_and_directory_entries_api/index.md
@@ -4,12 +4,16 @@ slug: Web/API/File_and_Directory_Entries_API
translation_of: Web/API/File_Handle_API
original_slug: Web/API/File_Handle_API
---
-
FileHandle API 可操作檔案,例如建立檔案、修改檔案內容 (不同於 File API)。而正在編輯中的部分,將使用回合制的鎖定機制,以避免發生競態 (Race) 問題。
-
API
-
建立 FileHandle
-
若要建立 FileHandle 物件,則需要 IndexedDB Database 。
-
-
var idbreq = indexedDB.open("MyTestDatabase");
+FileHandle API 可操作檔案,例如建立檔案、修改檔案內容 (不同於 [File](/zh-TW/docs/DOM/File) API)。而正在編輯中的部分,將使用回合制的鎖定機制,以避免發生競態 (Race) 問題。
+
+## API
+
+### 建立 FileHandle
+
+若要建立 FileHandle 物件,則需要 [IndexedDB Database](/zh-TW/docs/IndexedDB/IDBFactory#open)。
+
+```js hidden
+var idbreq = indexedDB.open("MyTestDatabase");
idbreq.onsuccess = function(){
var db = idbreq.result;
@@ -20,18 +24,24 @@ idbreq.onsuccess = function(){
console.log('handle', handle);
};
};
-
-
-
mozCreateFileHandle()
共使用
2 組參數
(Argument):1 組名稱與 1 組檔案類別 (Optional type)。但這 2 組參
數均只屬於敘述性參
數,不會用於資料庫。舉例來說,名稱可能是空白字串,而且不需為專屬字串。所以 API 根本不會注意這些參數值。
-
另請注意,上列程式碼僅會建立「暫時性檔案」,亦即當你保留 FileHandle 物件時,該檔案才會存在。如果你要在重新整理頁面/重新啟動 App 之後,仍能保留檔案,則必須將 Handle 儲存於更永久性的位置 (如資料庫本身之內) 中。
-
var transaction = db.transaction(["test"], "readwrite");
+```
+
+`mozCreateFileHandle()` 共使用 `2` 組參數(Argument):1 組名稱與 1 組檔案類別 (Optional type)。但這 2 組參數均只屬於敘述性參數,不會用於資料庫。舉例來說,名稱可能是空白字串,而且不需為專屬字串。所以 API 根本不會注意這些參數值。
+
+另請注意,上列程式碼僅會建立「暫時性檔案」,亦即當你保留 FileHandle 物件時,該檔案才會存在。如果你要在重新整理頁面/重新啟動 App 之後,仍能保留檔案,則必須將 Handle 儲存於更永久性的位置 (如資料庫本身之內) 中。
+
+```js
+var transaction = db.transaction(["test"], "readwrite");
var objectStore = transaction.objectStore("test");
objectStore.add(myFile, myKey).onsuccess = function(event) {
// The file is now referenced from database too.
}
-
-
FileHandle 介面
-
interface FileHandle
+```
+
+### FileHandle 介面
+
+```plain
+interface FileHandle
{
LockedFile open(optional DOMString mode);
DOMRequest getFile()
@@ -39,45 +49,37 @@ objectStore.add(myFile, myKey).onsuccess = function(event) {
readonly attribute DOMString type;
attribute Function? onabort;
attribute Function? onerror;
-};
-
-
- open([mode="readonly"])
-
- 可回傳 LockedFile 。mode
可為「readonly」或「
readwrite」。
-
- getFile()
-
- 針對檔案而回傳 DOMRequest 。若成功,就會收到以 File 物件形式呈現的唯讀「snapshot」檔案內容 (可用於任何接受 Blob 的地方,如 FileReader 或 XMLHttpRequest 等)。
- myFile.getFile().onsuccess = function(event) {
- var file = event.target.result;
- var transcation = myDatabase.transaction(["snapshots"], "readwrite");
- var objectStore = transaction.objectStore("snapshots");
- objectStore.add(file, snapshotKey).onsuccess = function(event) {
+};
+```
+
+- open(\[mode="readonly"])
+ - : 可回傳 [LockedFile](#LockedFile_interface)。`mode` 可為「` readonly」或「``readwrite」。 `
+- getFile()
+ - : 針對檔案而回傳 [DOMRequest](/zh-TW/docs/DOM/DOMRequest)。若成功,就會收到以 [File](/zh-TW/docs/DOM/File) 物件形式呈現的唯讀「snapshot」檔案內容 (可用於任何接受 [Blob](/zh-TW/docs/DOM/Blob) 的地方,如 [FileReader](/zh-TW/docs/DOM/FileReader) 或 [XMLHttpRequest](/zh-TW/docs/DOM/XMLHttpRequest) 等)。
+
+ ```js
+ myFile.getFile().onsuccess = function(event) {
+ var file = event.target.result;
+ var transcation = myDatabase.transaction(["snapshots"], "readwrite");
+ var objectStore = transaction.objectStore("snapshots");
+ objectStore.add(file, snapshotKey).onsuccess = function(event) {
// A new readonly copy of the file has been created.
- }
-}
-
-
-
- name
-
- 檔案名稱。
-
- type
-
- 代表 content-type。
-
- abort event
-
- 放棄已鎖定的檔案,就會發生此事件。
-
- error event
-
- 任何內部錯誤,都會發生此事件。
-
-
LockedFile 介面
-
interface LockedFile
+ }
+ }
+ ```
+- name
+ - : 檔案名稱。
+- type
+ - : 代表 content-type。
+- abort event
+ - : 放棄已鎖定的檔案,就會發生此事件。
+- error event
+ - : 任何內部錯誤,都會發生此事件。
+
+### LockedFile 介面
+
+```plain
+interface LockedFile
{
readonly attribute FileHandle fileHandle;
readonly attribute DOMString mode;
@@ -94,89 +96,71 @@ objectStore.add(myFile, myKey).onsuccess = function(event) {
attribute Function? oncomplete;
attribute Function? onabort;
attribute Function? onerror;
-};
-
-
- fileHandle
-
- 來自於解鎖的 FileHandle 物件。
-
- mode
-
- 「readonly」或「
readwrite」。
-
- active
-
- 一旦建立之後,就隨即啟動 LockedFile。此 LockedFile 是「可寫入存取 (Write access) 實際底層檔案」的唯一物件。LockedFile 上的作業,均於 isolation 之中執行;也就是說,只要啟動了 LockedFile,則此 LockedFile 的所有作業都一定會在底層檔案上依序執行,而不會與其他 LockedFiles 的作業交錯執行。
- 若停用了 LockedFile,則只要在同樣的 LockedFile 上執行讀/寫作業,都會丟出錯誤訊息。
-
-
-
- location
-
- 檔案中的位置 (Offset)。每次讀/寫作業之後,此數值均將自動變更。讀寫作業均從該 location 開始,而 null 代表檔案末端。
-
- getMetadata(parameters)
-
- 針對後設資料 (Metadata) 而回傳 FileRequest 。此參
數亦屬於物件,其中將參數名稱作為物件鍵值,布林值作為數值,進而非同步檢索既有的屬性。無數值則代表 true
。目前僅有 size
與 lastModified
為可能的參數。
-
- readAsArrayBuffer(size)
-
- 針對既有 size
的 ArrayBuffer ,回傳 FileRequest 。此作業均從 location
開始,另根據讀取位元組的數目,移動 location
。
-
- readAsText(size [, encoding])
-
- 針對既有 size
的字串,以既定的 encoding
回傳 FileRequest 。此作業均從 location
開始,另根據讀取位元組的數目,移動 location
。FileReader API 中的對等函式,也以相同方式運作。
- var lockedFile = myFile.open();
-var request = lockedFile.readAsText(3);
-request.onsuccess = function(event) {
- var text = request.result;
- // 3 characters have been read.
-}
-
-
-
- write(value)
-
- 針對成功/失敗的寫入作業,回傳 FileRequest 。寫入作業將從 location
開始,另根據寫入位元組的數目,移動位置。
- var lockedFile = myFile.open("readwrite");
-var request = lockedFile.write("foo");
-request.onsuccess = function(event) {
- // The string "foo" has been written.
-}
-
-
-
- append(value)
-
- 針對成功/失敗的附加 (Append) 作業,回傳 FileRequest 。不論 location
為何,該數值均附加於檔案末端。在附加資料完畢後,location
隨即設定為 null
。
-
- truncate([size])
-
- 針對成功/失敗的截斷 (Truncate) 作業,回傳 FileRequest。
-
- 如果是以單一參
數呼叫該函式,則截斷成功之後,則不論 location
為何,檔案將剩下第一個 size
的位元組。
-
- 若沒有用任何參
數呼叫該函式,則檔案將剩下 location
的第一個位元組。
-
- flush()
-
- 強制移轉緩衝過的資料至磁碟上,作業成功之後將回傳 FileRequest。此時即便 App 當機或非刻意中止,都能確保資料已經位於磁碟上了。
-
- abort()
-
- 停用 LockedFile 並取消全部尚未執行的作業。
-
- complete, abort, error events
-
-
FileRequest 介面
-
此類型的物件,均是由 LockedFile 介面的所有非同步作業所回傳。此介面繼承了 DOMRequest 並類似 IDBRequest ,同時還擁有 onprogress
事件。在成功之後,則可透過
result
屬性而取得必要檔案作業的結果。
-
interface FileRequest : DOMRequest
+};
+```
+
+- fileHandle
+ - : 來自於解鎖的 FileHandle 物件。
+- mode
+ - : 「`readonly`」或「`readwrite`」。
+- active
+ - : 一旦建立之後,就隨即啟動 LockedFile。此 LockedFile 是「可寫入存取 (Write access) 實際底層檔案」的唯一物件。LockedFile 上的作業,均於 [isolation](https://en.wikipedia.org/wiki/Isolation_%28database_systems%29) 之中執行;也就是說,只要啟動了 LockedFile,則此 LockedFile 的所有作業都一定會在底層檔案上依序執行,而不會與其他 LockedFiles 的作業交錯執行。
+
+ 若停用了 LockedFile,則只要在同樣的 LockedFile 上執行讀/寫作業,都會丟出錯誤訊息。
+- location
+ - : 檔案中的位置 (Offset)。每次讀/寫作業之後,此數值均將自動變更。讀寫作業均從該 location 開始,而 null 代表檔案末端。
+- getMetadata(parameters)
+ - : 針對後設資料 (Metadata) 而回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。此參數亦屬於物件,其中將參數名稱作為物件鍵值,布林值作為數值,進而非同步檢索既有的屬性。無數值則代表 `true`。目前僅有 `size` 與 `lastModified` 為可能的參數。
+- readAsArrayBuffer(size)
+ - : 針對既有` size `的 [ArrayBuffer](/en-US/docs/JavaScript/Typed_arrays/ArrayBuffer),回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。此作業均從 `location` 開始,另根據讀取位元組的數目,移動 `location`。
+- readAsText(size [, encoding])
+ - : 針對既有 `size` 的字串,以既定的` encoding` 回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。此作業均從 `location` 開始,另根據讀取位元組的數目,移動 `location`。[FileReader](/en-US/docs/DOM/FileReader) API 中的對等函式,也以相同方式運作。
+
+ ```js
+ var lockedFile = myFile.open();
+ var request = lockedFile.readAsText(3);
+ request.onsuccess = function(event) {
+ var text = request.result;
+ // 3 characters have been read.
+ }
+ ```
+- write(value)
+ - : 針對成功/失敗的寫入作業,回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。寫入作業將從 `location` 開始,另根據寫入位元組的數目,移動位置。
+
+ ```js
+ var lockedFile = myFile.open("readwrite");
+ var request = lockedFile.write("foo");
+ request.onsuccess = function(event) {
+ // The string "foo" has been written.
+ }
+ ```
+- append(value)
+ - : 針對成功/失敗的附加 (Append) 作業,回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。不論 `location` 為何,該數值均附加於檔案末端。在附加資料完畢後,`location` 隨即設定為 `null`。
+- truncate([size])
+ - : 針對成功/失敗的截斷 (Truncate) 作業,回傳 [FileRequest](/en-US/docs/WebAPI/FileHandle_API#FileRequest_interface)。
+
+ 如果是以單一參數呼叫該函式,則截斷成功之後,則**不論** `location` 為何,檔案將剩下第一個 `size` 的位元組。
+
+ 若沒有用任何參數呼叫該函式,則檔案將剩下 `location` 的第一個位元組。
+- flush()
+ - : 強制移轉緩衝過的資料至磁碟上,作業成功之後將回傳 FileRequest。此時即便 App 當機或非刻意中止,都能確保資料已經位於磁碟上了。
+- abort()
+ - : 停用 LockedFile 並取消全部尚未執行的作業。
+
+### FileRequest 介面
+
+此類型的物件,均是由 LockedFile 介面的所有非同步作業所回傳。此介面繼承了 [DOMRequest](/zh-TW/docs/DOM/DOMRequest) 並類似 [IDBRequest](/zh-TW/docs/IndexedDB/IDBRequest),同時還擁有 ` onprogress ``事件。在成功之後,則可透過` ` result ``屬性而取得必要檔案作業的結果。`
+
+```plain
+interface FileRequest : DOMRequest
{
readonly attribute LockedFile lockedFile;
attribute Function? onprogress;
-};
+};
+```
+
+## 說明
+
+### API 與 FileWriter 的差異?
-
說明
-
API 與 FileWriter 的差異?
-
FileWriter 規格 定義了 FileWriter,也就是用以呈現「可編輯的檔案」的物件。Public-webapps 討論串 則下了結論:若單一檔案同時寫入不同的實體 (Entity),將導致 API 成效不彰。最後就是 FileHandle API 應具備自己的 LockedFile 與交易機制。
+[FileWriter 規格](http://dev.w3.org/2009/dap/file-system/file-writer.html)定義了 FileWriter,也就是用以呈現「可編輯的檔案」的物件。[Public-webapps 討論串](http://lists.w3.org/Archives/Public/public-webapps/2012JanMar/0886.html)則下了結論:若單一檔案同時寫入不同的實體 (Entity),將導致 API 成效不彰。最後就是 FileHandle API 應具備自己的 LockedFile 與交易機制。
diff --git a/files/zh-tw/web/api/file_api/using_files_from_web_applications/index.md b/files/zh-tw/web/api/file_api/using_files_from_web_applications/index.md
index 71c2693b05da24..e02d896c8863ed 100644
--- a/files/zh-tw/web/api/file_api/using_files_from_web_applications/index.md
+++ b/files/zh-tw/web/api/file_api/using_files_from_web_applications/index.md
@@ -6,57 +6,62 @@ tags:
translation_of: Web/API/File/Using_files_from_web_applications
original_slug: Web/API/File/Using_files_from_web_applications
---
-
現在可以透過新增至HTML5 DOM的File API讓web內容要求使用者選取本地端的檔案後讀取被選取檔案中的內容。檔案的選取動作可以使用HTML的 input
元素,或是用拖曳檔案(drag and drop)的方式來完成。
+現在可以透過新增至 HTML5 DOM 的 File API 讓 web 內容要求使用者選取本地端的檔案後讀取被選取檔案中的內容。檔案的選取動作可以使用 HTML 的 [`input`](/en/DOM/HTMLInputElement) 元素,或是用拖曳檔案(drag and drop)的方式來完成。
-
如果你想要使用 DOM 檔案 API 的文件擴展或是其他Chrome 程式碼,你可以參考使用DOM檔案API在FireFox外觀代碼中 。
+如果你想要使用 DOM 檔案 API 的文件擴展或是其他 Chrome 程式碼,你可以參考[使用 DOM 檔案 API 在 FireFox 外觀代碼中](/en/Extensions/Using_the_DOM_File_API_in_chrome_code)。
-
使用HTML選擇本地檔案
+## 使用 HTML 選擇本地檔案
-
HTML 語法:
+HTML 語法:
-
<input type="file" id="input">
+```html
+
+```
-
File API 可以從 {{ domxref("File") }} 物件中讀取 {{ domxref("FileList") }} ,{{domxref("FileList") }} 內包含使用者所選取的檔案。
+File API 可以從 {{ domxref("File") }} 物件中讀取 {{ domxref("FileList") }} ,{{domxref("FileList") }} 內包含使用者所選取的檔案。
-
如果使用者只選擇一個檔案,那麼我們只需要考慮第一個檔案物件。
+如果使用者只選擇一個檔案,那麼我們只需要考慮第一個檔案物件。
-
使用 DOM 獲取選擇的檔案:
+使用 DOM 獲取選擇的檔案:
-
var selectedFile = document.getElementById('input').files[0];
+```js
+var selectedFile = document.getElementById('input').files[0];
+```
-
使用 jQuery 獲取選擇的檔案:
+使用 [jQuery](http://jquery.com/) 獲取選擇的檔案:
-
var selectedFile = $('#input').get(0).files[0];
+```js
+var selectedFile = $('#input').get(0).files[0];
-var selectedFile = $('#input')[0].files[0];
-
+var selectedFile = $('#input')[0].files[0];
+```
-
-
如果獲取 "files is undefined" 錯誤: 代表未選擇正確的 HTML 元素, 這時忘記 jQuery 回傳符合 DOM 元素的清單. 改使用 DOM 元素呼叫 "files" 方法.
-
-
-
使用 change event 獲取選擇的檔案
+> **備註:** 如果獲取 "files is undefined" 錯誤: 代表未選擇正確的 HTML 元素, 這時忘記 jQuery 回傳符合 DOM 元素的清單. 改使用 DOM 元素呼叫 "files" 方法.
-
使用File API選擇單一檔案是非常簡單的,如下
+## 使用 change event 獲取選擇的檔案
-
<input type="file" id="input" onchange="handleFiles(this.files)">
-
+使用 File API 選擇單一檔案是非常簡單的,如下
-
當使用者選取一個檔案,呼叫 handleFiles()
會得到一個 {{domxref("FileList") }} 的物件。{{domxref("FileList") }} 裡面還會有一個 {{domxref("File")}}
的物件,裡面的東西就是使用者選取的檔案。
+```html
+
+```
-
如果你想要讓使用者一次選擇多個檔案,可以在 input
元素中使用 multiple
的屬性:
+當使用者選取一個檔案,呼叫 `handleFiles()` 會得到一個 {{domxref("FileList") }} 的物件。{{domxref("FileList") }} 裡面還會有一個 `{{domxref("File")}}` 的物件,裡面的東西就是使用者選取的檔案。
-
<input type="file" id="input" multiple="true" onchange="handleFiles(this.files)">
+如果你想要讓使用者一次選擇多個檔案,可以在 `input` 元素中使用 `multiple` 的屬性:
-
+```html
+
+```
-
在上述這個例子中,檔案名單會傳遞到 handleFiles()
函數,其中包含了使用者選的每個檔案 {{domxref("File")}} 物件。
+在上述這個例子中,檔案名單會傳遞到 `handleFiles()` 函數,其中包含了使用者選的每個檔案 {{domxref("File")}} 物件。
-
使用 EventListener 動態地監聽
+### 使用 EventListener 動態地監聽
-
如果使用了其他的函數庫(jQuery ),你會需要使用 {{domxref("EventTarget.addEventListener()") }} 去監聽事件,例如:
+如果使用了其他的函數庫([jQuery](http://www.jquery.com/)),你會需要使用 {{domxref("EventTarget.addEventListener()") }} 去監聽事件,例如:
-
var inputElement = document.getElementById("inputField");
+```js
+var inputElement = document.getElementById("inputField");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
@@ -64,53 +69,53 @@ function handleFiles() {
/* now you can work with the file list */
}
-
+```
-
在這個例子中,handleFiles()
函數找尋檔案清單而非接收參數, 因為這樣增加的 event listeners 不能接受參數.
+在這個例子中,`handleFiles() `函數找尋檔案清單而非接收參數, 因為這樣增加的 event listeners 不能接受參數.
-
獲得選取檔案的資訊
+## 獲得選取檔案的資訊
-
由DOM提供的 {{domxref("FileList") }} 物件代表使用者選取的所有檔案,每個又是 {{domxref("File")}}
物件。可以藉由 {{domxref("FileList") }} 的 length 屬性得知使用者選取的檔案數量:
+由 DOM 提供的 {{domxref("FileList") }} 物件代表使用者選取的所有檔案,每個又是 `{{domxref("File")}} `物件。可以藉由 {{domxref("FileList") }} 的 length 屬性得知使用者選取的檔案數量:
-
var numFiles = files.length;
-
+```js
+var numFiles = files.length;
+```
-
使用陣列獲取 {{domxref("File")}} 物件:
+使用陣列獲取 {{domxref("File")}} 物件:
-
for (var i = 0; i < files.length; i++) {
+```js
+for (var i = 0; i < files.length; i++) {
var file = files[i];
..
}
-
+```
-
上述的例子顯示獲取在檔案清單裡所有檔案物件的方法。
+上述的例子顯示獲取在檔案清單裡所有檔案物件的方法。
-
{{domxref("File")}} 提供三個包含檔案重要訊息的屬性。
+{{domxref("File")}} 提供三個包含檔案重要訊息的屬性。
-
- name
- 唯讀的檔案名稱,並未包含檔案路徑。
- size
- 為 64 位元的整數,用以表示檔案的 byte 的長度。
- type
- 為唯讀字串。表示檔案的 MIME-type 。若是無法取得檔案的 Mime-type ,則其值會是一個空字串 ""
。
-
+- `name`
+ - : 唯讀的檔案名稱,並未包含檔案路徑。
+- `size`
+ - : 為 64 位元的整數,用以表示檔案的 byte 的長度。
+- `type`
+ - : 為唯讀字串。表示檔案的 MIME-type 。若是無法取得檔案的 Mime-type ,則其值會是一個空字串 `""`。
-
+## 使用 click() 方法隱藏檔案輸入元素
-
使用click() 方法隱藏檔案輸入元素
+從 Gecko 2.0 {{ geckoRelease("2.0") }}開始,為了顯示個人化開啟檔案的 UI 和使用者選擇的檔案可以隱藏 {{ HTMLElement("input") }} 元素和顯示個人化的設計。可以藉由設置 CSS 「display:none」 和對 {{ HTMLElement("input") }} 元素呼叫 `click()` 方法。
-
從 Gecko 2.0 {{ geckoRelease("2.0") }}開始,為了顯示個人化開啟檔案的UI和使用者選擇的檔案可以隱藏 {{ HTMLElement("input") }} 元素和顯示個人化的設計。可以藉由設置CSS 「display:none」 和對 {{ HTMLElement("input") }} 元素呼叫 click()
方法。
+HTML 如下:
-
HTML 如下:
+```html
+
+
Select some files
+```
-
<input type="file" id="fileElem" multiple="true" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
-<a href="#" id="fileSelect">Select some files</a>
-
+`doClick()` 方法:
-
doClick()
方法:
-
-
var fileSelect = document.getElementById("fileSelect"),
+```js
+var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem");
fileSelect.addEventListener("click", function (e) {
@@ -119,27 +124,29 @@ fileSelect.addEventListener("click", function (e) {
}
e.preventDefault(); // prevent navigation to "#"
}, false);
-
+```
-
很明顯的,可以使用CSS來設計新的上傳檔案的按鈕。
+很明顯的,可以使用 CSS 來設計新的上傳檔案的按鈕。
-
使用拖放選取檔案
+## 使用拖放選取檔案
-
使用者可以使用拖放來選取檔案,首先要設置放的區域,確定文件可以接收放的檔案,方法如下:
+使用者可以使用拖放來選取檔案,首先要設置放的區域,確定文件可以接收放的檔案,方法如下:
-
var dropbox;
+```js
+var dropbox;
dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
-
+```
-
在這個範例中,我們將 ID "dropbox" 設為放的區域,這是由於我們監聽了 dragenter 、
dragover
和 drop
事件。
+在這個範例中,我們將 ID "dropbox" 設為放的區域,這是由於我們監聽了 ` dragenter 、`` dragover `和 `drop`事件。
-
我們甚至不需要處理 dragenter 和
dragover
事件,所以這些函數很簡單。他們阻止了事件的傳播和預設事件的發生:
+我們甚至不需要處理 ` dragenter 和 ``dragover`事件,所以這些函數很簡單。他們阻止了事件的傳播和預設事件的發生:
-
function dragenter(e) {
+```js
+function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
@@ -148,11 +155,12 @@ function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
-
+```
-
神奇的 drop()
函數:
+神奇的 `drop()` 函數:
-
function drop(e) {
+```js
+function drop(e) {
e.stopPropagation();
e.preventDefault();
@@ -161,19 +169,17 @@ function dragover(e) {
handleFiles(files);
}
-
-
-
這邊我們用 dataTransfer
來獲取檔案清單, 並傳遞給 handleFiles()
.。 我們可以發現,不論使用拖放或是其他取得檔案,處理檔案的方式都是相同。
+```
-
-
+`這邊我們用 dataTransfer `來獲取檔案清單, 並傳遞給 `handleFiles()`.。 我們可以發現,不論使用拖放或是其他取得檔案,處理檔案的方式都是相同。
-
範例:顯示選取的圖片
+## 範例:顯示選取的圖片
-
假設要開發一個分享照片的網站,想使用 HTML5 來讓使用者在上傳圖片前預覽縮圖。簡單來說就是像先前討論地一樣建立 input 元素或是 drop 區域,接著再呼叫類似 handleFiles()
的函數。
+假設要開發一個分享照片的網站,想使用 HTML5 來讓使用者在上傳圖片前預覽縮圖。簡單來說就是像先前討論地一樣建立 input 元素或是 drop 區域,接著再呼叫類似 `handleFiles()` 的函數。
-
function handleFiles(files) {
- for (var i = 0; i < files.length; i++) {
+```js
+function handleFiles(files) {
+ for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
@@ -191,47 +197,52 @@ function dragover(e) {
reader.readAsDataURL(file);
}
}
-
+```
-
這邊迴圈處理了使用者選取的每個檔案並檢查每個檔案的類型是不是圖檔(藉由使用正規表達式檢查是否符合字串 "image.*")。每一個是圖片的檔案,我們創建一個 img
元素。CSS 被使用來美化外框、陰影、還有設定圖片的尺寸,所以那些並不需要在這邊寫入。
+這邊迴圈處理了使用者選取的每個檔案並檢查每個檔案的類型是不是圖檔(藉由使用正規表達式檢查是否符合字串 "image.\*")。每一個是圖片的檔案,我們創建一個 `img` 元素。CSS 被使用來美化外框、陰影、還有設定圖片的尺寸,所以那些並不需要在這邊寫入。
-
為了使圖片可以在DOM裡面更容易被找到,所以每個圖片都有設定CSS class “obj”。 我們也在每個圖檔標記 file
屬性以辨認 File
;這使我們更容易取得真正要上傳的圖檔。最後我們使用{{ domxref("Node.appendChild()") }} 在文件中增加縮圖的元素。
+為了使圖片可以在 DOM 裡面更容易被找到,所以每個圖片都有設定 CSS class “obj”。 我們也在每個圖檔標記 `file` 屬性以辨認 [`File`](/en/DOM/File);這使我們更容易取得真正要上傳的圖檔。最後我們使用{{ domxref("Node.appendChild()") }} 在文件中增加縮圖的元素。
-
FileReader
處理要非同步讀取的圖檔並跟 img
元素連接。在創建 FileReader
物件後,我們設置了 onload
並 呼叫 readAsDataURL()
在背景呼叫讀取的程序。當所有圖檔都被讀取時,他們被轉換為傳到 onload callback 的
data
URL。 這個範例簡易的設置img
元素的 src
屬性來讀取圖檔並在螢幕上顯示。
+[`FileReader`](/en/DOM/FileReader) 處理要非同步讀取的圖檔並跟 `img` 元素連接。在創建 `FileReader` 物件後,我們設置了 `onload `並 呼叫 `readAsDataURL()` 在背景呼叫讀取的程序。當所有圖檔都被讀取時,他們被轉換為傳到 ` onload callback 的`` data ` URL。 這個範例簡易的設置`img` 元素的 `src` 屬性來讀取圖檔並在螢幕上顯示。
-
使用 object URLs
+## 使用 object URLs
-
Gecko 2.0 {{ geckoRelease("2.0") }} 支援 DOM 的{{ domxref("window.URL.createObjectURL()") }} 和 {{ domxref("window.URL.revokeObjectURL()") }} 方法。可以藉由這些方法創建表示任何為 DOM File
物件的 data URL 字串,包含了使用者電腦上的檔案。
+Gecko 2.0 {{ geckoRelease("2.0") }} 支援 DOM 的{{ domxref("window.URL.createObjectURL()") }} 和 {{ domxref("window.URL.revokeObjectURL()") }} 方法。可以藉由這些方法創建表示任何為 DOM [`File`](/en/DOM/File) 物件的 data URL 字串,包含了使用者電腦上的檔案。
-
可以使 File
物件作為 HTML 元素 URL 的參考,創建 object URL 的方法:
+可以使 [`File`](/en/DOM/File) 物件作為 HTML 元素 URL 的參考,創建 object URL 的方法:
-
var objectURL = window.URL.createObjectURL(fileObj);
-
+```js
+var objectURL = window.URL.createObjectURL(fileObj);
+```
-
object URL 為表示 File
物件的字串。即使已經對相同檔案創建了 object URL,每次呼叫 {{ domxref("window.URL.createObjectURL()") }},就會創建一個 object URL。當文檔卸載時他們將會被自動釋放,如果要動態地使用,需要呼叫 {{ domxref("window.URL.revokeObjectURL()") }} 釋放:
+object URL 為表示 [`File`](/en/DOM/File) 物件的字串。即使已經對相同檔案創建了 object URL,每次呼叫 {{ domxref("window.URL.createObjectURL()") }},就會創建一個 object URL。當文檔卸載時他們將會被自動釋放,如果要動態地使用,需要呼叫 {{ domxref("window.URL.revokeObjectURL()") }} 釋放:
-
window.URL.revokeObjectURL(objectURL);
+```js
+window.URL.revokeObjectURL(objectURL);
+```
-
範例:使用 object URLs 顯示圖片
+## 範例:使用 object URLs 顯示圖片
-
{{ geckoRelease("2.0") }}這個範例使用 object URLs 顯示圖像縮圖。此外也顯示了其他包含檔案名稱和檔案大小的訊息。線上範例 (註:瀏覽器版本要求 11/22 之後的火狐版本)。
+{{ geckoRelease("2.0") }}這個範例使用 object URLs 顯示圖像縮圖。此外也顯示了其他包含檔案名稱和檔案大小的訊息。[線上範例](/samples/domref/file-click-demo.html) (註:瀏覽器版本要求 11/22 之後的火狐版本)。
-
註: 這個 API 在較早的 Firefox 4 betas 存在但是 11/22 號後的版本有改變, 所以確定瀏覽器在最新的版本!
+> **備註:** 這個 API 在較早的 Firefox 4 betas 存在但是 11/22 號後的版本有改變, 所以確定瀏覽器在最新的版本!
-
HTML:
+HTML:
-
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
-<a href="#" id="fileSelect">Select some files</a>
-<div id="fileList">
- <p>No files selected!</p>
-</div>
-
+```html
+
+
Select some files
+
+```
-
This establishes our file {{ HTMLElement("input") }} element, as well as a link that invokes the file picker, since we keep the file input hidden to prevent that less-than-attractive UI from being displayed. This is explained above in the section Using hidden file input elements using the click() method , as is the doClick()
method that invokes the file picker.
+This establishes our file {{ HTMLElement("input") }} element, as well as a link that invokes the file picker, since we keep the file input hidden to prevent that less-than-attractive UI from being displayed. This is explained above in the section [Using hidden file input elements using the click() method](<#使用click()_方法隱藏檔案輸入元素>), as is the `doClick()` method that invokes the file picker.
-
The handleFiles()
method follows:
+The `handleFiles()` method follows:
-
var fileSelect = document.getElementById("fileSelect"),
+```js
+var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
@@ -244,11 +255,11 @@ fileSelect.addEventListener("click", function (e) {
function handleFiles(files) {
if (!files.length) {
- fileList.innerHTML = "<p>No files selected!</p>";
+ fileList.innerHTML = "No files selected!
";
}
else {
var list = document.createElement("ul");
- for (var i = 0; i < files.length; i++) {
+ for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
@@ -267,51 +278,49 @@ function handleFiles(files) {
fileList.appendChild(list);
}
}
-
+```
-
This starts by fetching the URL of the {{ HTMLElement("div") }} with the ID "fileList". This is the block into which we'll insert out file list, including thumbmails.
+This starts by fetching the URL of the {{ HTMLElement("div") }} with the ID "fileList". This is the block into which we'll insert out file list, including thumbmails.
-
If the {{ domxref("FileList") }} object passed to handleFiles()
is null
, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:
+If the {{ domxref("FileList") }} object passed to `handleFiles()` is `null`, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:
-
- A new unordered list ({{ HTMLElement("ul") }} element is created.
- The new list element is inserted into the {{ HTMLElement("div") }} block by calling its {{ domxref("element.appendChild()") }} method.
- For each {{ domxref("File") }} in the {{ domxref("FileList") }} represented by files
:
-
- Create a new list item ({{ HTMLElement("li") }}) element and insert it into the list.
- Create a new image ({{ HTMLElement("img") }}) element.
- Set the image's source to a new object URL representing the file, using {{ domxref("window.URL.createObjectURL()") }} to create the blob URL.
- Set the image's height to 60 pixels.
- Set up the image's load event handler to release the object URL, since it's no longer needed once the image has been loaded. This is done by calling the {{ domxref("window.URL.revokeObjectURL()") }} method, passing in the object URL string as specified by img.src
.
- Append the new list item to the list.
-
-
-
+1. A new unordered list ({{ HTMLElement("ul") }} element is created.
+2. The new list element is inserted into the {{ HTMLElement("div") }} block by calling its {{ domxref("element.appendChild()") }} method.
+3. For each {{ domxref("File") }} in the {{ domxref("FileList") }} represented by `files`:
-
範例:上傳檔案
+ 1. Create a new list item ({{ HTMLElement("li") }}) element and insert it into the list.
+ 2. Create a new image ({{ HTMLElement("img") }}) element.
+ 3. Set the image's source to a new object URL representing the file, using {{ domxref("window.URL.createObjectURL()") }} to create the blob URL.
+ 4. Set the image's height to 60 pixels.
+ 5. Set up the image's load event handler to release the object URL, since it's no longer needed once the image has been loaded. This is done by calling the {{ domxref("window.URL.revokeObjectURL()") }} method, passing in the object URL string as specified by `img.src`.
+ 6. Append the new list item to the list.
-
接下來這個範例顯示如何非同步的上傳檔案到伺服器。
+## 範例:上傳檔案
-
新增上傳的工作
+接下來這個範例顯示如何非同步的上傳檔案到伺服器。
-
接續先前創建縮圖的範例,將每個縮圖都設置 CSS class “obj”, 這使得我們可以很容易地使用{{ domxref("Document.querySelectorAll()") }} 選擇使用者要上傳的圖檔,例如:
+### 新增上傳的工作
-
function sendFiles() {
+接續先前創建縮圖的範例,將每個縮圖都設置 CSS class “obj”, 這使得我們可以很容易地使用{{ domxref("Document.querySelectorAll()") }} 選擇使用者要上傳的圖檔,例如:
+
+```js
+function sendFiles() {
var imgs = document.querySelectorAll(".obj");
- for (var i = 0; i < imgs.length; i++) {
+ for (var i = 0; i < imgs.length; i++) {
new FileUpload(imgs[i], imgs[i].file);
}
}
-
+```
-
第二行創建了 imgs
陣列,存放著所有文件中 CSS class 為 “obj” 的 Node。在這個範例中,我們使用這個來創建縮圖。Once we have that list, it's trivial to go through the list, creating a new FileUpload
instance for each. Each of these handles uploading the corresponding file.
+第二行創建了 `imgs `陣列,存放著所有文件中 CSS class 為 “obj” 的 Node。在這個範例中,我們使用這個來創建縮圖。Once we have that list, it's trivial to go through the list, creating a new `FileUpload` instance for each. Each of these handles uploading the corresponding file.
-
處理上傳檔案的程序
+### 處理上傳檔案的程序
-
FileUpload
函數接受圖檔和檔案.
+`FileUpload` 函數接受圖檔和檔案.
-
function FileUpload(img, file) {
+```js
+function FileUpload(img, file) {
var reader = new FileReader();
this.ctrl = createThrobber(img);
var xhr = new XMLHttpRequest();
@@ -337,28 +346,25 @@ function handleFiles(files) {
};
reader.readAsBinaryString(file);
}
-
+```
-
FileUpload()
函數創建被用來顯示上傳進度的 throbber,接著創建 {{domxref("XMLHttpRequest")}} 上傳檔案.
+`FileUpload()` 函數創建被用來顯示上傳進度的 throbber,接著創建 {{domxref("XMLHttpRequest")}} 上傳檔案.
-
傳輸資料前的幾個準備工作:
+傳輸資料前的幾個準備工作:
-
- The XMLHttpRequest
's upload "progress" listener is set to update the throbber with new percentage information, so that as the upload progresses, the throbber will be updated based on the latest information.
- The XMLHttpRequest
's upload "load" event handler is set to update the throbber with 100% as the progress information (to ensure the progress indicator actually reaches 100%, in case of granularity quirks during the process). It then removes the throbber, since it's no longer needed. This causes the throbber to disappear once the upload is complete.
- The request to upload the image file is opened by calling XMLHttpRequest
's open()
method to start generating a POST request.
- The MIME type for the upload is set by calling the XMLHttpRequest
function overrideMimeType()
. In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all, depending on your use case.
- The FileReader
object is used to convert the file to a binary string.
- Finally, when the content is loaded the XMLHttpRequest
function sendAsBinary()
is called to upload the file's content.
-
+1. The `XMLHttpRequest`'s upload "progress" listener is set to update the throbber with new percentage information, so that as the upload progresses, the throbber will be updated based on the latest information.
+2. The `XMLHttpRequest`'s upload "load" event handler is set to update the throbber with 100% as the progress information (to ensure the progress indicator actually reaches 100%, in case of granularity quirks during the process). It then removes the throbber, since it's no longer needed. This causes the throbber to disappear once the upload is complete.
+3. The request to upload the image file is opened by calling `XMLHttpRequest`'s `open()` method to start generating a POST request.
+4. The MIME type for the upload is set by calling the `XMLHttpRequest` function `overrideMimeType()`. In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all, depending on your use case.
+5. The `FileReader` object is used to convert the file to a binary string.
+6. Finally, when the content is loaded the `XMLHttpRequest` function `sendAsBinary()` is called to upload the file's content.
-
-
註: 範例中非標準的 sendAsBinary
方法已經在 Gecko 31 {{ geckoRelease(31) }} 廢棄且很快將會被移除。可以改使用標準的 send(Blob data)。
-
+> **備註:** 範例中非標準的 `sendAsBinary` 方法已經在 Gecko 31 {{ geckoRelease(31) }} 廢棄且很快將會被移除。可以改使用標準的 `send(Blob data)。`
-
非同步處理上傳檔案的程序
+### 非同步處理上傳檔案的程序
-
function fileUpload(file) {
+```js
+function fileUpload(file) {
// Please report improvements to: marco.buratto at tiscali.it
var fileName = file.name,
@@ -374,7 +380,7 @@ function handleFiles(files) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
- if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
+ if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
if (xhr.responseText != "") {
alert(xhr.responseText); // display response.
@@ -392,17 +398,15 @@ function handleFiles(files) {
xhr.send(body);
return true;
}
-
+```
-
使用二進制數據時,這些程式碼還需要修改。
+_使用二進制數據時,這些程式碼還需要修改。_
-
你也可以參考這些文章
+## 你也可以參考這些文章
-
+- `{{domxref("File")}}`
+- {{domxref("FileList")}}
+- {{domxref("FileReader") }}
+- [Using XMLHttpRequest](/en/DOM/XMLHttpRequest/Using_XMLHttpRequest)
+- [Using the DOM File API in chrome code](/en/Extensions/Using_the_DOM_File_API_in_chrome_code)
+- `{{domxref("XMLHttpRequest")}}`
diff --git a/files/zh-tw/web/api/filelist/index.md b/files/zh-tw/web/api/filelist/index.md
index 828ccb73fb7a53..fdd6c97195ac56 100644
--- a/files/zh-tw/web/api/filelist/index.md
+++ b/files/zh-tw/web/api/filelist/index.md
@@ -3,80 +3,64 @@ title: FileList
slug: Web/API/FileList
translation_of: Web/API/FileList
---
-
{{APIRef("File API")}}
+{{APIRef("File API")}}
-
FileList
型別物件通常來自 HTML {{HTMLElement("input")}} 元素 {{domxref("Document_Object_Model", "DOM")}} 物件的 files
屬性({{Glossary("property/JavaScript", "property")}})。你可以操作 FileList
物件來存取使用者透過 <input type="file">
元素所選取的檔案,或由拖放操作所產生的檔案(請參考 {{domxref("DataTransfer")}} 物件的更多使用細節)。
+`FileList` 型別物件通常來自 HTML {{HTMLElement("input")}} 元素 {{domxref("Document_Object_Model", "DOM")}} 物件的 `files` 屬性({{Glossary("property/JavaScript", "property")}})。你可以操作 `FileList` 物件來存取使用者透過 `
` 元素所選取的檔案,或由拖放操作所產生的檔案(請參考 {{domxref("DataTransfer")}} 物件的更多使用細節)。
-
-
在 {{Gecko("1.9.2")}} 之前,{{HTMLElement("input")}} 元素只支援一次選取一個檔案,這代表了 FileList
只能夠包含一個 File
物件。從 {{Gecko("1.9.2")}} 開始,假如 <input>
元素的 multiple
屬性(attribute)為 true,則 FileList 就可能會包含多個檔案。
-
+> **備註:** 在 {{Gecko("1.9.2")}} 之前,{{HTMLElement("input")}} 元素只支援一次選取一個檔案,這代表了 `FileList` 只能夠包含一個 `File` 物件。從 {{Gecko("1.9.2")}} 開始,假如 `
` 元素的 `multiple` 屬性(attribute)為 true,則 FileList 就可能會包含多個檔案。
-
使用 FileList
+## 使用 FileList
-
所有 <input>
元素節點的 {{domxref("Document_Object_Model", "DOM")}} 物件都擁有 files
屬性({{Glossary("property/JavaScript", "property")}}),此屬性即為 FileList
,是一個可藉此存取使用者選取之檔案的類陣列物件。以下範例展示了一個 type
屬性({{Glossary("attribute")}})值為 file
的 HTML <input>
元素:
+所有 `
` 元素節點的 {{domxref("Document_Object_Model", "DOM")}} 物件都擁有 `files` 屬性({{Glossary("property/JavaScript", "property")}}),此屬性即為 `FileList`,是一個可藉此存取使用者選取之檔案的類陣列物件。以下範例展示了一個 `type` 屬性({{Glossary("attribute")}})值為 `file` 的 HTML `
` 元素:
-
<input id="fileItem" type="file">
-
+```html
+
+```
-
下面範例演示了如何取得 <input>
元素節點中所包含的第一個 {{domxref("File")}} 型別物件:
+下面範例演示了如何取得 `
` 元素節點中所包含的第一個 {{domxref("File")}} 型別物件:
-
var file = document.getElementById('fileItem').files[0];
-
+```js
+var file = document.getElementById('fileItem').files[0];
+```
-
方法概觀
+## 方法概觀
-
-
-
- File item (index);
-
-
-
+| `File item(index);` |
+| ------------------- |
-
屬性
+## 屬性
-
-
-
-
-
-
-
-
- length
- integer
- 表示 FileList
物件中的檔案數量,唯讀。
-
-
-
+| 屬性名稱 | 型別 | 描述 |
+| -------- | --------- | ---------------------------------------- |
+| `length` | `integer` | 表示 `FileList` 物件中的檔案數量,唯讀。 |
-
方法
+## 方法
-
item()
+### item()
-
回傳 FileList
中指定索引的 {{domxref("File")}} 物件。
+回傳 `FileList` 中指定索引的 {{domxref("File")}} 物件。
-
File item(
+```js
+File item(
index
);
-
+```
-
參數
+#### 參數
-
- index
- 要取得的檔案之索引(起始於零)。
-
+- `index`
+ - : 要取得的檔案之索引(起始於零)。
-
回傳值
+#### 回傳值
-
要求的 {{domxref("File")}} 物件。
+要求的 {{domxref("File")}} 物件。
-
範例
+## 範例
-
此範例演示了迭代所有之使用者於 <input>
元素選取的檔案:
+此範例演示了迭代所有之使用者於 `
` 元素選取的檔案:
-
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
+```js
+// fileInput is an HTML input element:
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (similar to NodeList)
@@ -84,7 +68,7 @@ var files = fileInput.files;
var file;
// loop through files
-for (var i = 0; i < files.length; i++) {
+for (var i = 0; i < files.length; i++) {
// get item
file = files.item(i);
@@ -93,22 +77,23 @@ for (var i = 0; i < files.length; i++) {
alert(file.name);
}
-
+```
-
以下是更完整的範例:
+以下是更完整的範例:
-
<!DOCTYPE HTML>
-<html>
-<head>
-</head>
-<body>
-<!--multiple is set to allow multiple files to be selected-->
+```html
+
+
+
+
+
+
-<input id="myfiles" multiple type="file">
+
-</body>
+
-<script>
+
-</html>
+
+```
-
規範
+## 規範
-
+- [File upload state](http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#concept-input-type-file-selected) (HTML5 working draft)
-
參見
+## 參見
-
+- [在網頁應用程式中使用本地檔案](/zh-TW/docs/Using_files_from_web_applications)
+- {{domxref("File")}}
+- {{domxref("FileReader")}}
diff --git a/files/zh-tw/web/api/filereader/index.md b/files/zh-tw/web/api/filereader/index.md
index bfb0668aa2464d..67f4d0794aab4c 100644
--- a/files/zh-tw/web/api/filereader/index.md
+++ b/files/zh-tw/web/api/filereader/index.md
@@ -9,102 +9,90 @@ tags:
- Reference
translation_of: Web/API/FileReader
---
-
{{APIRef("File API")}}
-
-
藉由 FileReader
物件,Web 應用程式能以非同步(asynchronously)方式讀取儲存在用戶端的檔案(或原始資料暫存)內容,可以使用 {{domxref("File")}} 或 {{domxref("Blob")}} 物件指定要讀取的資料。
-
-
File 物件可以從使用者於 {{HTMLElement("input")}} 元素選擇之檔案所回傳的 {{domxref("FileList")}} 物件當中取得,或是來自拖放操作 所產生的 {{domxref("DataTransfer")}} 物件之中,也能由 {{domxref("HTMLCanvasElement")}} 物件(元素物件)執行 mozGetAsFile()
方法後回傳。
-
-
{{AvailableInWorkers}}
-
-
建構式
-
-
- {{domxref("FileReader.FileReader", "FileReader()")}}
- 建立新的 FileReader
物件。
-
-
-
請參考在網頁應用程式中使用本地檔案 的更多細節與範例。
-
-
屬性
-
-
- {{domxref("FileReader.error")}} {{readonlyinline}}
- 此 {{domxref("DOMException")}} 類型的物件記錄了讀取資料時發生的錯誤資訊。
- {{domxref("FileReader.readyState")}} {{readonlyinline}}
- 表示目前 FileReader
狀態的數字,其代表的意義為:
-
-
-
- EMPTY
- 0
- 尚未讀入任何資料。
-
-
- LOADING
- 1
- 正在讀入資料。
-
-
- DONE
- 2
- 完成資料讀取。
-
-
-
-
- {{domxref("FileReader.result")}} {{readonlyinline}}
- 讀入的資料內容。只有在讀取完成之後此屬性才有效,而資料的格式則取決於是由哪一個方法進行讀取。
-
-
-
事件處理器
-
-
- {{domxref("FileReader.onabort")}}
- {{event("abort")}} 事件處理器,於讀取被中斷時觸發。
- {{domxref("FileReader.onerror")}}
- {{event("error")}} 事件處理器,於讀取發生錯誤時觸發。
- {{domxref("FileReader.onload")}}
- {{event("load")}} 事件處理器,於讀取完成時觸發。
- {{domxref("FileReader.onloadstart")}}
- {{event("loadstart")}} 事件處理器,於讀取開始時觸發。
- {{domxref("FileReader.onloadend")}}
- {{event("loadend")}} 事件處理器,於每一次讀取結束之後觸發(不論成功或失敗),會於 onload
或 onerror
事件處理器之後才執行。
- {{domxref("FileReader.onprogress")}}
- {{event("progress")}} 事件處理器,於讀取 {{domxref("Blob")}} 內容時觸發。
-
-
-
-
FileReader
物件繼承自 {{domxref("EventTarget")}},其所有的事件也都能夠透過 {{domxref("EventTarget.addEventListener()","addEventListener")}} 方法來註冊事件監聽器。
-
-
-
方法
-
-
- {{domxref("FileReader.abort()")}}
- 中斷目前的讀取,此方法回傳後屬性 readyState
將會是 DONE
。
- {{domxref("FileReader.readAsArrayBuffer()")}}
- 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result
將以 {{domxref("ArrayBuffer")}} 物件來表示讀入的資料內容。
- {{domxref("FileReader.readAsBinaryString()")}} {{non-standard_inline}}
- 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result
將以字串型式來表示讀入的原始二進位資料(raw binary data)。
- {{domxref("FileReader.readAsDataURL()")}}
- 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result
將以 data:
URL 格式(base64 編碼)的字串來表示讀入的資料內容。
- {{domxref("FileReader.readAsText()")}}
- 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result
將以文字字串型式來表示讀入的資料內容。
-
-
-
規範
+{{APIRef("File API")}}
+
+藉由 `FileReader` 物件,Web 應用程式能以非同步(asynchronously)方式讀取儲存在用戶端的檔案(或原始資料暫存)內容,可以使用 {{domxref("File")}} 或 {{domxref("Blob")}} 物件指定要讀取的資料。
+
+File 物件可以從使用者於 {{HTMLElement("input")}} 元素選擇之檔案所回傳的 {{domxref("FileList")}} 物件當中取得,或是來自[拖放操作](/docs/Web/Guide/HTML/Drag_and_drop)所產生的 {{domxref("DataTransfer")}} 物件之中,也能由 {{domxref("HTMLCanvasElement")}} 物件(元素物件)執行 `mozGetAsFile()` 方法後回傳。
+
+{{AvailableInWorkers}}
+
+## 建構式
+
+- {{domxref("FileReader.FileReader", "FileReader()")}}
+ - : 建立新的 `FileReader` 物件。
+
+請參考[在網頁應用程式中使用本地檔案](/docs/Using_files_from_web_applications)的更多細節與範例。
+
+## 屬性
+
+- {{domxref("FileReader.error")}} {{readonlyinline}}
+ - : 此 {{domxref("DOMException")}} 類型的物件記錄了讀取資料時發生的錯誤資訊。
+- {{domxref("FileReader.readyState")}} {{readonlyinline}}
+ - : 表示目前 `FileReader` 狀態的數字,其代表的意義為:
+
+
+
+
+ EMPTY
+ 0
+ 尚未讀入任何資料。
+
+
+ LOADING
+ 1
+ 正在讀入資料。
+
+
+ DONE
+ 2
+ 完成資料讀取。
+
+
+
+- {{domxref("FileReader.result")}} {{readonlyinline}}
+ - : 讀入的資料內容。只有在讀取完成之後此屬性才有效,而資料的格式則取決於是由哪一個方法進行讀取。
+
+### 事件處理器
+
+- {{domxref("FileReader.onabort")}}
+ - : {{event("abort")}} 事件處理器,於讀取被中斷時觸發。
+- {{domxref("FileReader.onerror")}}
+ - : {{event("error")}} 事件處理器,於讀取發生錯誤時觸發。
+- {{domxref("FileReader.onload")}}
+ - : {{event("load")}} 事件處理器,於讀取完成時觸發。
+- {{domxref("FileReader.onloadstart")}}
+ - : {{event("loadstart")}} 事件處理器,於讀取開始時觸發。
+- {{domxref("FileReader.onloadend")}}
+ - : {{event("loadend")}} 事件處理器,於每一次讀取結束之後觸發(不論成功或失敗),會於 `onload` 或 `onerror` 事件處理器之後才執行。
+- {{domxref("FileReader.onprogress")}}
+ - : {{event("progress")}} 事件處理器,於讀取 {{domxref("Blob")}} 內容時觸發。
+
+> **備註:** `FileReader` 物件繼承自 {{domxref("EventTarget")}},其所有的事件也都能夠透過 {{domxref("EventTarget.addEventListener()","addEventListener")}} 方法來註冊事件監聽器。
+
+## 方法
+
+- {{domxref("FileReader.abort()")}}
+ - : 中斷目前的讀取,此方法回傳後屬性 `readyState` 將會是 `DONE`。
+- {{domxref("FileReader.readAsArrayBuffer()")}}
+ - : 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 `result` 將以 {{domxref("ArrayBuffer")}} 物件來表示讀入的資料內容。
+- {{domxref("FileReader.readAsBinaryString()")}} {{non-standard_inline}}
+ - : 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 `result` 將以字串型式來表示讀入的原始二進位資料(raw binary data)。
+- {{domxref("FileReader.readAsDataURL()")}}
+ - : 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 `result` 將以 `data:` URL 格式(base64 編碼)的字串來表示讀入的資料內容。
+- {{domxref("FileReader.readAsText()")}}
+ - : 開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 `result` 將以文字字串型式來表示讀入的資料內容。
+
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.FileReader")}}
-
參見
+## 參見
-
+- [在網頁應用程式中使用本地檔案](/docs/Using_files_from_web_applications)
+- {{domxref("File")}}
+- {{domxref("Blob")}}
diff --git a/files/zh-tw/web/api/filesystem/index.md b/files/zh-tw/web/api/filesystem/index.md
index 785d2148190a89..3aa4c1beca7fd1 100644
--- a/files/zh-tw/web/api/filesystem/index.md
+++ b/files/zh-tw/web/api/filesystem/index.md
@@ -5,47 +5,39 @@ tags:
- 檔案系統
translation_of: Web/API/FileSystem
---
-
{{APIRef("File System API")}} {{non-standard_header}}
+{{APIRef("File System API")}} {{non-standard_header}}
-
FileSystem
實作文件和目錄介面,描述一個檔案系統。在任何檔案系統上,這個物件包含
{{domxref("FileSystemEntry.filesystem", "filesystem")}}的特性。某些網頁瀏覽器提供額外的API去創建和管理檔案系統,如Google Chrome的{{domxref("LocalFileSystem.requestFileSystem", "requestFileSystem()")}}函式。
+**`FileSystem `**`實作文件和目錄介面,描述一個檔案系統。在任何檔案系統上,這個物件包含` {{domxref("FileSystemEntry.filesystem", "filesystem")}}的特性。某些網頁瀏覽器提供額外的 API 去創建和管理檔案系統,如 Google Chrome 的{{domxref("LocalFileSystem.requestFileSystem", "requestFileSystem()")}}函式。
-
-
此介面並非標準API, 代表規格並未依造標準制定, 因此必須注意並非所有網頁瀏覽器都有實作此介面, 有實作的網頁瀏覽器可能只有實作一小部分. 請在Browser compatibility 查看更多細節.
-
+> **備註:** 此介面並非標準 API, 代表規格並未依造標準制定, 因此必須注意並非所有網頁瀏覽器都有實作此介面, 有實作的網頁瀏覽器可能只有實作一小部分. 請在[Browser compatibility](#browser_compatibility) 查看更多細節.
-
基礎概念
+## 基礎概念
-
存取 FileSystem
物件的兩種方法:
+存取 `FileSystem` 物件的兩種方法:
-
- 你可以直接要求一個使用window.requestFileSystem(),
只用在你的網頁應用程式的沙盒類型 FileSystem 物件。如果要求成功,將會執行
callback handler去接收描述檔案系統的FileSystem物件參數。
- 你可以從檔案系統接口物件取得,透過他的{{domxref("FileSystemEntry.filesystem", "filesystem")}}特性
-
+1. 你可以直接要求一個使用`window.requestFileSystem(),`只用在你的網頁應用程式的沙盒類型 `FileSystem 物件。如果要求成功,將會執行`callback handler 去接收描述檔案系統的`FileSystem物件參數。`
+2. 你可以從檔案系統接口物件取得,透過他的{{domxref("FileSystemEntry.filesystem", "filesystem")}}特性
-
屬性
+## 屬性
-
- {{domxref("FileSystem.name")}} {{ReadOnlyInline}}
- {{domxref("USVString")}} 代表檔案系統的名稱. 此名稱在整個已宣告的檔案系統清單中是唯一的。
- {{domxref("FileSystem.root")}} {{ReadOnlyInline}}
- {{domxref("FileSystemDirectoryEntry")}} 物件表示檔案系統的根目錄。 透過此物件, 你可以取得權限存取所有檔案系統中的文件和目錄
-
+- {{domxref("FileSystem.name")}} {{ReadOnlyInline}}
+ - : {{domxref("USVString")}} 代表檔案系統的名稱. 此名稱在整個已宣告的檔案系統清單中是唯一的。
+- {{domxref("FileSystem.root")}} {{ReadOnlyInline}}
+ - : {{domxref("FileSystemDirectoryEntry")}} 物件表示檔案系統的根目錄。 透過此物件, 你可以取得權限存取所有檔案系統中的文件和目錄
-
規範
+## 規範
{{Specifications}}
-
This API has no official W3C or WHATWG specification.
+This API has no official W3C or WHATWG specification.
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.FileSystem")}}
-
參見
+## 參見
-
+- [File and Directory Entries API](/zh-TW/docs/Web/API/File_and_Directory_Entries_API)
+- [Introduction to the File System API](/zh-TW/docs/Web/API/File_and_Directory_Entries_API/Introduction)
+- {{domxref("FileSystemEntry")}}, {{domxref("FileSystemFileEntry")}}, and {{domxref("FileSystemDirectoryEntry")}}
+- MSDN 文章: [WebKitFileSystem object](https://msdn.microsoft.com/library/mt732564)
diff --git a/files/zh-tw/web/api/formdata/using_formdata_objects/index.md b/files/zh-tw/web/api/formdata/using_formdata_objects/index.md
index 1b5db804a13991..e5de07a6fce121 100644
--- a/files/zh-tw/web/api/formdata/using_formdata_objects/index.md
+++ b/files/zh-tw/web/api/formdata/using_formdata_objects/index.md
@@ -3,13 +3,14 @@ title: Using FormData Objects
slug: Web/API/FormData/Using_FormData_Objects
translation_of: Web/API/FormData/Using_FormData_Objects
---
-
The FormData
object lets you compile a set of key/value pairs to send using XMLHttpRequest
. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's {{domxref("HTMLFormElement.submit","submit()")}} method would use to send the data if the form's encoding type were set to multipart/form-data
.
+The [`FormData`](/en-US/docs/Web/API/FormData) object lets you compile a set of key/value pairs to send using [`XMLHttpRequest`](/en-US/docs/Web/API/XMLHttpRequest). It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's {{domxref("HTMLFormElement.submit","submit()")}} method would use to send the data if the form's encoding type were set to `multipart/form-data`.
-
+## Creating a FormData object from scratch
-
You can build a FormData
object yourself, instantiating it then appending fields to it by calling its {{domxref("FormData.append","append()")}} method, like this:
+You can build a `FormData` object yourself, instantiating it then appending fields to it by calling its {{domxref("FormData.append","append()")}} method, like this:
-
var formData = new FormData();
+```js
+var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
@@ -18,7 +19,7 @@ formData.append("accountnum", 123456); // number 123456 is immediately converted
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object
-var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
+var content = 'hey! '; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
@@ -26,57 +27,63 @@ formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
-
+```
-
Note: The fields "userfile" and "webmasterfile" both contain a file. The number assigned to the field "accountnum" is immediately converted into a string by the
FormData.append()
method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string:
if the value is neither a Blob nor a File, the value is converted to a string ).
+> **備註:** The fields "userfile" and "webmasterfile" both contain a file. The number assigned to the field "accountnum" is immediately converted into a string by the [`FormData.append()`]() method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string: **if the value is neither a Blob nor a File, the value is converted to a string**).
-
This example builds a FormData
instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the XMLHttpRequest
method send()
to send the form's data. The field "webmasterfile" is a {{domxref("Blob")}}. A Blob
object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on Blob
, inheriting blob functionality and expanding it to support files on the user's system. In order to build a Blob
you can invoke the {{domxref("Blob.Blob","Blob() constructor")}}.
+This example builds a `FormData` instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the `XMLHttpRequest` method [`send()`]() to send the form's data. The field "webmasterfile" is a {{domxref("Blob")}}. A `Blob` object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on `Blob`, inheriting blob functionality and expanding it to support files on the user's system. In order to build a `Blob` you can invoke the {{domxref("Blob.Blob","Blob() constructor")}}.
-
+## Retrieving a FormData object from an HTML form
-
To construct a FormData
object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the FormData
object:
+To construct a `FormData` object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the `FormData` object:
-
var formData = new FormData(someFormElement);
-
+```js
+var formData = new FormData(someFormElement);
+```
-
For example:
+For example:
-
var formElement = document.querySelector("form");
+```js
+var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
-
+```
-
You can also append additional data to the FormData
object between retrieving it from a form and sending it, like this:
+You can also append additional data to the `FormData` object between retrieving it from a form and sending it, like this:
-
var formElement = document.querySelector("form");
+```js
+var formElement = document.querySelector("form");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
formData.append("serialnumber", serialNumber++);
-request.send(formData);
+request.send(formData);
+```
-
This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable.
+This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable.
-
+## 使用 FormData 物件傳送檔案
-
You can also send files using FormData
. Simply include an {{ HTMLElement("input") }} element of type file
in your {{htmlelement("form")}}:
+You can also send files using `FormData`. Simply include an {{ HTMLElement("input") }} element of type `file` in your {{htmlelement("form")}}:
-
<form enctype="multipart/form-data" method="post" name="fileinfo">
- <label>Your email address:</label>
- <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
- <label>Custom file label:</label>
- <input type="text" name="filelabel" size="12" maxlength="32" /><br />
- <label>File to stash:</label>
- <input type="file" name="file" required />
- <input type="submit" value="Stash the file!" />
-</form>
-<div></div>
-
+```html
+
+ Your email address:
+
+ Custom file label:
+
+ File to stash:
+
+
+
+
+```
-
Then you can send it using code like the following:
+Then you can send it using code like the following:
-
var form = document.forms.namedItem("fileinfo");
+```js
+var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
@@ -90,29 +97,29 @@ form.addEventListener('submit', function(ev) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
- oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
+ oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file. ";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
-
+```
-
-
Note : If you pass in a reference to the form the method specified in the form will be used over the method specified in the open() call.
-
+> **備註:** If you pass in a reference to the form the method specified in the form will be used over the method specified in the open() call.
-
You can also append a {{ domxref("File") }} or {{ domxref("Blob") }} directly to the {{ domxref("FormData") }} object, like this:
+You can also append a {{ domxref("File") }} or {{ domxref("Blob") }} directly to the {{ domxref("FormData") }} object, like this:
-
data.append("myfile", myBlob, "filename.txt");
-
+```js
+data.append("myfile", myBlob, "filename.txt");
+```
-
When using the {{domxref("FormData.append","append()")}} method it is possible to use the third optional parameter to pass a filename inside the Content-Disposition
header that is sent to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.
+When using the {{domxref("FormData.append","append()")}} method it is possible to use the third optional parameter to pass a filename inside the `Content-Disposition` header that is sent to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.
-
You can also use FormData
with jQuery if you set the right options:
+You can also use `FormData` with jQuery if you set the right options:
-
var fd = new FormData(document.querySelector("form"));
+```js
+var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "stash.php",
@@ -121,17 +128,15 @@ $.ajax({
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
-
+```
-
+## Submitting forms and uploading files via AJAX _without_ `FormData` objects
-
If you want to know how to serialize and submit a form via AJAX without using FormData objects, please read this paragraph .
+If you want to know how to serialize and submit a form via [AJAX](/zh-TW/docs/AJAX) _without_ using FormData objects, please read [this paragraph](/zh-TW/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files).
-
參見
+## 參見
-
+- [Using XMLHttpRequest](/zh-TW/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest)
+- {{domxref("HTMLFormElement")}}
+- {{domxref("Blob")}}
+- [Typed Arrays](/zh-TW/docs/Web/JavaScript/Typed_arrays)
diff --git a/files/zh-tw/web/api/fullscreen_api/index.md b/files/zh-tw/web/api/fullscreen_api/index.md
index ce9a21d7f3b91d..9e55a5b02b41ad 100644
--- a/files/zh-tw/web/api/fullscreen_api/index.md
+++ b/files/zh-tw/web/api/fullscreen_api/index.md
@@ -3,27 +3,29 @@ title: 使用全螢幕模式
slug: Web/API/Fullscreen_API
translation_of: Web/API/Fullscreen_API
---
-
{{DefaultAPISidebar("Fullscreen API")}}
+{{DefaultAPISidebar("Fullscreen API")}}
-
全螢幕 API 提供一個簡便的方式使網頁可以使用佔用使用者的整個螢幕的方式來顯示內容。該 API 讓您能夠容易地指示瀏覽器使某個元素及其子系(如有)佔用整個螢幕,並隱藏螢幕上所有瀏覽器使用者介面及其他應用程式。
+全螢幕 API 提供一個簡便的方式使網頁可以使用佔用使用者的整個螢幕的方式來顯示內容。該 API 讓您能夠容易地指示瀏覽器使某個元素及其子系(如有)佔用整個螢幕,並隱藏螢幕上所有瀏覽器使用者介面及其他應用程式。
-
目前並非所有瀏覽器均使用 API 的沒有前綴的版本。請查閱有關前綴以及名稱差異的表格(您也可以使用 Fscreen 來提供跨瀏覽器 API 存取)。
+> **備註:** 目前並非所有瀏覽器均使用 API 的沒有前綴的版本。請查閱有關前綴以及名稱差異的表格(您也可以使用 Fscreen 來提供跨瀏覽器 API 存取)。
-
啟動全螢幕模式
+## 啟動全螢幕模式
-
如果您有一個元素打算以全螢幕模式展示(例如 {{ HTMLElement("video") }}),您可以呼叫該元素之 {{ domxref("Element.requestFullscreen()") }} 方法使之以全螢幕模式顯示。
+如果您有一個元素打算以全螢幕模式展示(例如 {{ HTMLElement("video") }}),您可以呼叫該元素之 {{ domxref("Element.requestFullscreen()") }} 方法使之以全螢幕模式顯示。
-
考慮此 {{ HTMLElement("video") }} 元素:
+考慮此 {{ HTMLElement("video") }} 元素:
-
<video controls id="myvideo">
- <source src="somevideo.webm"></source>
- <source src="somevideo.mp4"></source>
-</video>
-
+```html
+
+
+
+
+```
-
我們可以使用指令碼將此影片全螢幕顯示:
+我們可以使用指令碼將此影片全螢幕顯示:
-
var elem = document.getElementById("myvideo");
+```js
+var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
@@ -33,77 +35,76 @@ if (elem.requestFullscreen) {
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
-
+```
-
呈現差異
+### 呈現差異
-
值得留意的是,Gecko 及 WebKit 的實作有關鍵分別:Gecko 會增加 CSS 規則讓全螢幕的元素展延至填滿整個螢幕:"width: 100%; height: 100%
"。WebKit 則不會執行此動作,取而代之的是把該元素置中,並以原先的大小顯示。要取得同樣的全螢幕行為,您需要為該元素自行添加 "width: 100%; height: 100%;
" 的 CSS 規則:
+值得留意的是,Gecko 及 WebKit 的實作有關鍵分別:Gecko 會增加 CSS 規則讓全螢幕的元素展延至填滿整個螢幕:"`width: 100%; height: 100%`"。WebKit 則不會執行此動作,取而代之的是把該元素置中,並以原先的大小顯示。要取得同樣的全螢幕行為,您需要為該元素自行添加 "`width: 100%; height: 100%;`" 的 CSS 規則:
-
#myvideo:-webkit-full-screen {
+```css
+#myvideo:-webkit-full-screen {
width: 100%;
height: 100%;
}
-
+```
-
另一方面,如果您嘗試在 Gecko 上模擬 WebKit 的行為,您需要把呈現的元素放置在另一個實際調整為全螢幕的元素裡面,再使用 CSS 規則來調整內部元素至您想要的外觀。
+另一方面,如果您嘗試在 Gecko 上模擬 WebKit 的行為,您需要把呈現的元素放置在另一個實際調整為全螢幕的元素裡面,再使用 CSS 規則來調整內部元素至您想要的外觀。
-
通知
+### 通知
-
如果成功進入全螢幕模式,包含該元素的文件將會接收到 {{ event("fullscreenchange") }} 事件。當離開全螢幕模式時,則會收到 {{ event("fullscreenchange") }} 事件。注意 {{ event("fullscreenchange") }} 事件並不提供任何資訊指示進入或離開全螢幕模式,但如果文件的 {{ domxref("document.fullscreenElement", "fullscreenElement") }} 屬性的值不為 null,則表示您正在處於全螢幕模式。
+如果成功進入全螢幕模式,包含該元素的文件將會接收到 {{ event("fullscreenchange") }} 事件。當離開全螢幕模式時,則會收到 {{ event("fullscreenchange") }} 事件。注意 {{ event("fullscreenchange") }} 事件並不提供任何資訊指示進入或離開全螢幕模式,但如果文件的 {{ domxref("document.fullscreenElement", "fullscreenElement") }} 屬性的值不為 null,則表示您正在處於全螢幕模式。
-
全螢幕要求失敗
+### 全螢幕要求失敗
-
並不是所有情況下都保證可以進入全螢幕模式。例如,{{ HTMLElement("iframe") }} 元素含有 {{ HTMLAttrXRef("allowfullscreen", "iframe") }} 屬性來選擇是否容許其內容能以全螢幕方式呈現。而且,例如視窗式外掛程式等的某些內容並不可以在全螢幕模式中顯示。把無法呈現為全螢幕的元素設定為全螢幕模式的嘗試都沒有作用,而要求顯示為全螢幕的元素會接收到 mozfullscreenerror
事件。當全螢幕要求失敗時,Firefox 會在網頁主控台上紀錄一則錯誤訊息,解釋要求失敗的原因。但在 Chrome 以及新版的 Opera 上,則不會產生這些錯誤訊息。
+並不是所有情況下都保證可以進入全螢幕模式。例如,{{ HTMLElement("iframe") }} 元素含有 {{ HTMLAttrXRef("allowfullscreen", "iframe") }} 屬性來選擇是否容許其內容能以全螢幕方式呈現。而且,例如視窗式外掛程式等的某些內容並不可以在全螢幕模式中顯示。把無法呈現為全螢幕的元素設定為全螢幕模式的嘗試都沒有作用,而要求顯示為全螢幕的元素會接收到 `mozfullscreenerror` 事件。當全螢幕要求失敗時,Firefox 會在網頁主控台上紀錄一則錯誤訊息,解釋要求失敗的原因。但在 Chrome 以及新版的 Opera 上,則不會產生這些錯誤訊息。
-
-
注意: 全螢幕要求必須在事件處理常式中呼叫,否則將會被拒絕。
-
+> **備註:** 全螢幕要求必須在事件處理常式中呼叫,否則將會被拒絕。
-
離開全螢幕模式
+## 離開全螢幕模式
-
使用者永遠可以自行離開全螢幕模式,詳見 Things your users want to know 。您也可以呼叫 {{domxref("Document.exitFullscreen()")}} 方法來達到相同效果。
+使用者永遠可以自行離開全螢幕模式,詳見 [Things your users want to know](#things_your_users_want_to_know)。您也可以呼叫 {{domxref("Document.exitFullscreen()")}} 方法來達到相同效果。
-
其他資訊
+## 其他資訊
-
{{ domxref("document") }} 提供一些附加資訊,對於開發全螢幕網頁應用程式的時候非常有用:
+{{ domxref("document") }} 提供一些附加資訊,對於開發全螢幕網頁應用程式的時候非常有用:
-
- {{ domxref("document.fullscreenElement", "fullscreenElement") }}
- fullscreenElement
屬性傳回正在顯示為全螢幕模式的 {{ domxref("element") }}。如其為非 null 值,表示文件目前在全螢幕模式。如其為 null,表示文件目前不在全螢幕模式。
- {{ domxref("document.fullscreenEnabled", "fullscreenEnabled") }}
- fullscreenEnabled
屬性傳回文件是否容許您要求進入全螢幕訊息。
-
+- {{ domxref("document.fullscreenElement", "fullscreenElement") }}
+ - : `fullscreenElement` 屬性傳回正在顯示為全螢幕模式的 {{ domxref("element") }}。如其為非 null 值,表示文件目前在全螢幕模式。如其為 null,表示文件目前不在全螢幕模式。
+- {{ domxref("document.fullscreenEnabled", "fullscreenEnabled") }}
+ - : `fullscreenEnabled` 屬性傳回文件是否容許您要求進入全螢幕訊息。
-
使用者可能想了解的訊息
+## 使用者可能想了解的訊息
-
您可能會讓使用者知道他們可以按 ESC 或 F11 鍵來離開全螢幕模式。
+您可能會讓使用者知道他們可以按
ESC 或
F11 鍵來離開全螢幕模式。
-
此外,瀏覽其他頁面、切換分頁、或切換到其他應用程式(例如按 鍵)亦會離開全螢幕模式。
+此外,瀏覽其他頁面、切換分頁、或切換到其他應用程式(例如按 鍵)亦會離開全螢幕模式。
-
範例
+## 範例
-
In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and fullscreen presentation of the video.
+In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and fullscreen presentation of the video.
-
查看示例
+[查看示例](/samples/domref/fullscreen.html)
-
監視 Enter 鍵
+### 監視 Enter 鍵
-
When the page is loaded, this code is run to set up an event listener to watch for the 'enter' key.
+When the page is loaded, this code is run to set up an event listener to watch for the 'enter' key.
-
document.addEventListener("keydown", function(e) {
+```js
+document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
toggleFullScreen();
}
}, false);
-
+```
-
Toggling fullscreen mode
+### Toggling fullscreen mode
-
This code is called when the user hits the Enter key, as seen above.
+This code is called when the user hits the Enter key, as seen above.
-
function toggleFullScreen() {
- if (!document.fullscreenElement && // alternative standard method
- !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods
+```js
+function toggleFullScreen() {
+ if (!document.fullscreenElement && // alternative standard method
+ !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
@@ -125,64 +126,56 @@ if (elem.requestFullscreen) {
}
}
}
-
+```
-
This starts by looking at the value of the fullscreenElement
attribute on the {{ domxref("document") }} (checking it prefixed with both moz
, ms
,
and webkit
). If it's null
, the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling either {{ domxref("element.mozRequestFullScreen()") }} msRequestFullscreen()
or webkitRequestFullscreen()
, depending on which is available.
+This starts by looking at the value of the `fullscreenElement` attribute on the {{ domxref("document") }} (checking it prefixed with both `moz`,` ms`,` `and `webkit`). If it's `null`, the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling either {{ domxref("element.mozRequestFullScreen()") }} `msRequestFullscreen()`or `webkitRequestFullscreen()`, depending on which is available.
-
If fullscreen mode is already active (fullscreenElement
is non-null
), we call {{ domxref("document.mozCancelFullScreen()") }}, msExitFullscreen
or webkitExitFullscreen()
, again depending on which browser is in use.
+If fullscreen mode is already active (`fullscreenElement` is non-`null`), we call {{ domxref("document.mozCancelFullScreen()") }}, `msExitFullscreen` or `webkitExitFullscreen()`, again depending on which browser is in use.
-
瀏覽器兼容性
+## 瀏覽器兼容性
-
Document.fullscreen
+### Document.fullscreen
{{Compat("api.Document.fullscreen")}}
-
Document.fullscreenElement
+### Document.fullscreenElement
{{Compat("api.Document.fullscreenElement")}}
-
Document.fullscreenEnabled
+### Document.fullscreenEnabled
{{Compat("api.Document.fullscreenEnabled")}}
-
Document.exitFullscreen
+### Document.exitFullscreen
{{Compat("api.Document.exitFullscreen")}}
-
Element.requestFullscreen
+### Element.requestFullscreen
{{Compat("api.Element.requestFullscreen")}}
+## 規範
-
規範
+[Fullscreen API](http://fullscreen.spec.whatwg.org/)
-
Fullscreen API
+## 非標準方法
-
非標準方法
+These are some of the methods that browsers implemented before the standard was drafted. Having the standard methods described above it's better to avoid using the following ones:
-
These are some of the methods that browsers implemented before the standard was drafted. Having the standard methods described above it's better to avoid using the following ones:
+- [`window.fullScreen`](/zh-TW/docs/DOM/window.fullScreen) (Firefox)
+- `HTMLMediaElement.webkitDisplayingFullscreen`
+- `HTMLMediaElement.webkitEnterFullscreen`
+- `HTMLMediaElement.webkitExitFullscreen`
+- `HTMLMediaElement.webkitSupportsFullscreen`
-
- window.fullScreen
(Firefox)
- HTMLMediaElement.webkitDisplayingFullscreen
- HTMLMediaElement.webkitEnterFullscreen
- HTMLMediaElement.webkitExitFullscreen
- HTMLMediaElement.webkitSupportsFullscreen
-
+## 參見
-
參見
-
-
- {{ domxref("element.mozRequestFullScreen()") }}
- {{ domxref("element.mozCancelFullScreen()") }}
- {{ domxref("document.mozFullScreen") }}
- {{ domxref("document.mozFullScreenElement") }}
- {{ domxref("document.mozFullScreenEnabled") }}
- {{ cssxref(":-moz-full-screen") }}
- {{ cssxref(":-moz-full-screen-ancestor") }}
- {{ HTMLAttrXRef("allowfullscreen", "iframe") }}
-
-
-
+- {{ domxref("element.mozRequestFullScreen()") }}
+- {{ domxref("element.mozCancelFullScreen()") }}
+- {{ domxref("document.mozFullScreen") }}
+- {{ domxref("document.mozFullScreenElement") }}
+- {{ domxref("document.mozFullScreenEnabled") }}
+- {{ cssxref(":-moz-full-screen") }}
+- {{ cssxref(":-moz-full-screen-ancestor") }}
+- {{ HTMLAttrXRef("allowfullscreen", "iframe") }}
+- [Blog post: Firefox's HTML full-screen API enabled in Nightly builds](http://blog.pearce.org.nz/2011/11/firefoxs-html-full-screen-api-enabled.html)
diff --git a/files/zh-tw/web/api/gainnode/gain/index.md b/files/zh-tw/web/api/gainnode/gain/index.md
index d086d538f3204d..4e81c0a336e760 100644
--- a/files/zh-tw/web/api/gainnode/gain/index.md
+++ b/files/zh-tw/web/api/gainnode/gain/index.md
@@ -5,41 +5,36 @@ tags:
- API
translation_of: Web/API/GainNode/gain
---
-
{{ APIRef("Web Audio API") }}
+{{ APIRef("Web Audio API") }}
-
-
{{ domxref("GainNode") }} 介面的 gain
屬性是 a-rate {{domxref("AudioParam")}},代表增益的數值。
-
+{{ domxref("GainNode") }} 介面的 `gain` 屬性是 [a-rate](/zh-TW/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}},代表增益的數值。
-
語法
+## 語法
-
var audioCtx = new AudioContext();
+```js
+var audioCtx = new AudioContext();
var gainNode = audioCtx.createGain();
gainNode.gain.value = 0.5;
-
+```
-
傳回值
+### 傳回值
-
一個 {{domxref("AudioParam")}}.
+一個 {{domxref("AudioParam")}}.
-
-
註: 雖然傳回的 AudioParam
是唯讀的,但是它所代表的值可以更改。
-
+> **備註:** 雖然傳回的 `AudioParam` 是唯讀的,但是它所代表的值可以更改。
-
範例
+## 範例
-
{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}
+{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}
-
規格
+## 規格
{{Specifications}}
-
瀏覽器相容度
+## 瀏覽器相容度
{{Compat("api.GainNode.gain")}}
-
參見
+## 參見
-
+- [Using the Web Audio API](/zh-TW/docs/Web_Audio_API/Using_Web_Audio_API)
diff --git a/files/zh-tw/web/api/gainnode/index.md b/files/zh-tw/web/api/gainnode/index.md
index ed988de2f6ecc7..731c8f7968c045 100644
--- a/files/zh-tw/web/api/gainnode/index.md
+++ b/files/zh-tw/web/api/gainnode/index.md
@@ -3,15 +3,13 @@ title: GainNode
slug: Web/API/GainNode
translation_of: Web/API/GainNode
---
-
{{ APIRef("Web Audio API") }}
+{{ APIRef("Web Audio API") }}
-
-
GainNode
介面代表的是音量改變。 這是 {{domxref("AudioNode")}} 音訊處理模組,可以對輸入的訊號做增益 (gain) 後輸出。一個 GainNode
有一個輸入和一個輸出,兩者有相同的聲道數。
-
+`GainNode` 介面代表的是音量改變。 這是 {{domxref("AudioNode")}} 音訊處理模組,可以對輸入的訊號做增益 (gain) 後輸出。一個 `GainNode` 有一個輸入和一個輸出,兩者有相同的聲道數。
-
增益 (gain) 是無單位的數值,隨時間變化,會用來和所有輸入聲道的取樣做相乘。 如果更改的話,新的增益會用 de-zippering 演算法處理,以避免輸出聲音出現難聽的「喀」聲。
+增益 (gain) 是無單位的數值,隨時間變化,會用來和所有輸入聲道的取樣做相乘。 如果更改的話,新的增益會用 de-zippering 演算法處理,以避免輸出聲音出現難聽的「喀」聲。
-
+![The GainNode is increasing the gain of the output.](webaudiogainnode.png)
@@ -38,40 +36,34 @@ translation_of: Web/API/GainNode
-
Constructor
+## Constructor
-
- {{domxref("GainNode.GainNode", "GainNode()")}}
- Creates a new instance of an GainNode object.
-
+- {{domxref("GainNode.GainNode", "GainNode()")}}
+ - : Creates a new instance of an GainNode object.
-
Properties
+## Properties
-
Inherits properties from its parent, {{domxref("AudioNode")}} .
+_Inherits properties from its parent,_ _{{domxref("AudioNode")}}_.
-
- {{domxref("GainNode.gain")}} {{readonlyinline}}
- 是 a-rate {{domxref("AudioParam")}} ,代表增益值
-
+- {{domxref("GainNode.gain")}} {{readonlyinline}}
+ - : 是 [a-rate](/zh-TW/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} ,代表增益值
-
Methods
+## Methods
-
No specific method; inherits methods from its parent, {{domxref("AudioNode")}} .
+_No specific method; inherits methods from its parent,_ _{{domxref("AudioNode")}}_.
-
Example
+## Example
-
{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}
+{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}
-
Specifications
+## Specifications
{{Specifications}}
-
Browser compatibility
+## Browser compatibility
{{Compat("api.GainNode")}}
-
See also
+## See also
-
+- [Using the Web Audio API](/zh-TW/docs/Web_Audio_API/Using_Web_Audio_API)
diff --git a/files/zh-tw/web/api/geolocation/index.md b/files/zh-tw/web/api/geolocation/index.md
index 979373ea6fbc76..a0498871db99b0 100644
--- a/files/zh-tw/web/api/geolocation/index.md
+++ b/files/zh-tw/web/api/geolocation/index.md
@@ -11,43 +11,37 @@ tags:
- TopicStub
translation_of: Web/API/Geolocation
---
-
{{APIRef("Geolocation API")}}
+{{APIRef("Geolocation API")}}
-
Geolocation
介面代表一個物件可以透過你的網頁程式去獲得你的裝置位置。這個介面提供了網站或應用程式根據使用者的位置去客製化呈現的內容。
+**`Geolocation`** 介面代表一個物件可以透過你的網頁程式去獲得你的裝置位置。這個介面提供了網站或應用程式根據使用者的位置去客製化呈現的內容。
-
{{domxref("Navigator")}} 此物件實作了 {{domxref("Navigator.geolocation")}} 介面。
+{{domxref("Navigator")}} 此物件實作了 {{domxref("Navigator.geolocation")}} 介面。
-
-
備註: 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。
-
+> **備註:** 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。
-
性質
+## 性質
-
Geolocation
介面沒有繼承也沒有時做任何方法 。
+_`Geolocation` 介面沒有繼承也沒有時做任何方法_。
-
方法
+## 方法
-
Geolocation
介面沒有繼承任何方法 。
+**`Geolocation` 介面沒有繼承任何方法**。
-
- {{domxref("Geolocation.getCurrentPosition()")}}
- 取得裝置當前位置,並回傳{{domxref("Position")}}。
- {{domxref("Geolocation.watchPosition()")}}
- 返回一個長整數,註冊一個回呼函數。這個方法是用來註冊一個處理的函式,當使用者的裝置位置更新時,這個函式所傳入的回呼函式(callback function) 就會自動被呼叫。
- {{domxref("Geolocation.clearWatch()")}}
- 移除指定註冊的 watchPosition()
。
-
+- {{domxref("Geolocation.getCurrentPosition()")}}
+ - : 取得裝置當前位置,並回傳{{domxref("Position")}}。
+- {{domxref("Geolocation.watchPosition()")}}
+ - : 返回一個長整數,註冊一個回呼函數。這個方法是用來註冊一個處理的函式,當使用者的裝置位置更新時,這個函式所傳入的回呼函式(callback function) 就會自動被呼叫。
+- {{domxref("Geolocation.clearWatch()")}}
+ - : 移除指定註冊的` watchPosition()`。
-
規格
+## 規格
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Geolocation")}}
-
請參考
+## 請參考
-
+- [Using geolocation](/zh-TW/docs/WebAPI/Using_geolocation)
diff --git a/files/zh-tw/web/api/geolocation_api/index.md b/files/zh-tw/web/api/geolocation_api/index.md
index 150ede18ac7efd..f03adc718b4246 100644
--- a/files/zh-tw/web/api/geolocation_api/index.md
+++ b/files/zh-tw/web/api/geolocation_api/index.md
@@ -4,63 +4,66 @@ slug: Web/API/Geolocation_API
translation_of: Web/API/Geolocation_API
original_slug: Web/API/Geolocation/Using_geolocation
---
-
Web Apps 若需要使用者的位置,可透過 Geolocation API 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。
+Web Apps 若需要使用者的位置,可透過 **Geolocation API** 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。
-
地理位置定位 (Geolocation) 物件
+## 地理位置定位 (Geolocation) 物件
-
Geolocation API,是透過 navigator.geolocation
物件
所發佈。
+Geolocation API,是透過 [`navigator.geolocation`](/zh-TW/docs/Web/API/window.navigator.geolocation) `物件`所發佈。
-
若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:
+若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:
-
if ("geolocation" in navigator) {
+```js
+if ("geolocation" in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
-
+```
-
注意: 在 Firefox 24 之後的版本,即使停用此 API,
navigator
中的「
geolocation」也同樣回傳
true。此問題已根據規格而於
Firefox 25 中修正 (
bug 884921 )。
+> **備註:** 在 Firefox 24 之後的版本,即使停用此 API,`navigator `中的「`geolocation」也同樣回傳` `true。此問題已根據規格而於` [Firefox 25](/zh-TW/docs/Mozilla/Firefox/Releases/25/Site_Compatibility) 中修正 ([bug 884921](https://bugzilla.mozilla.org/show_bug.cgi?id=884921))。
-
取得目前位置
+### 取得目前位置
-
若要取得使用者目前的位置,可呼叫 getCurrentPosition()
函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。
- 若不論定位精確度而想儘快固定單一位置,則可使用 getCurrentPosition()
。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,getCurrentPosition()
可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。
+若要取得使用者目前的位置,可呼叫 `getCurrentPosition()` 函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。
+若不論定位精確度而想儘快固定單一位置,則可使用 `getCurrentPosition()`。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,`getCurrentPosition()` 可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。
-
+> **備註:** 依預設值,[`getCurrentPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.getCurrentPosition) 將儘快回傳較低精確度的結果。若不論精確度而只要儘快獲得答案,則可使用 [`getCurrentPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.getCurrentPosition)。舉例來說,搭載 GPS 的裝置可能需要一段時間才能取得 GPS 定位資訊,所以可能將低精確度的資料 (IP 位置或 Wifi) 回傳至 [`getCurrentPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.getCurrentPosition)。
-
navigator.geolocation.getCurrentPosition(function(position) {
+```js
+navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
-});
+});
+```
-
一旦取得定位位置之後,上列範例隨即將執行 do_something()
函式。
+一旦取得定位位置之後,上列範例隨即將執行 `do_something() `函式。
-
觀看目前位置
+### 觀看目前位置
-
如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 watchPosition() 函式
完成。watchPosition()
所具備的輸入參數與 getCurrentPosition()
相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 getCurrentPosition(),因此為選填
。
+如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 `watchPosition() 函式`完成。[`watchPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.watchPosition) 所具備的輸入參數與 `getCurrentPosition() `相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 `getCurrentPosition(),因此為選填`。
-
+> **備註:** 不需啟動 [`getCurrentPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.getCurrentPosition) 呼叫,亦可使用 [`watchPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.watchPosition)。
-
var watchID = navigator.geolocation.watchPosition(function(position) {
+```js
+var watchID = navigator.geolocation.watchPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
}
-);
+);
+```
-
watchPosition()
函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 clearWatch()
函式,即可停止觀看使用者的位置。
+`watchPosition()` 函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 `clearWatch() `函式,即可停止觀看使用者的位置。
-
navigator.geolocation.clearWatch(watchID);
-
+```plain
+navigator.geolocation.clearWatch(watchID);
+```
-
微調回應
+### 微調回應
-
getCurrentPosition()
與 watchPosition()
均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 PositionOptions
物件 (選填)。
+[`getCurrentPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.getCurrentPosition) 與 [`watchPosition()`](/zh-TW/docs/Web/API/window.navigator.geolocation.watchPosition) 均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 `PositionOptions` 物件 (選填)。
-
對 watchPosition
的呼叫應類似如下:
+對 [`watchPosition`](/zh-TW/docs/Web/API/window.navigator.geolocation.watchPosition) 的呼叫應類似如下:
-
function geo_success(position) {
+```js
+function geo_success(position) {
do_something(position.coords.latitude, position.coords.longitude);
}
@@ -74,35 +77,40 @@ var geo_options = {
timeout : 27000
};
-var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+```
-
現成的 watchPosition Demo:http://www.thedotproduct.org/experiments/geo/
+現成的 watchPosition Demo:
-
敘述位置
+## 敘述位置
-
以 Position
物件參照 Coordinates
物件,即可敘述使用者的位置。
+以 `Position` 物件參照 `Coordinates` 物件,即可敘述使用者的位置。
-
處理錯誤
+## 處理錯誤
-
在呼叫 getCurrentPosition()
或 watchPosition() 時,
若獲得錯誤回呼函式,則錯誤回呼函式的第一組參數將為 PositionError 物件:
+在呼叫 `getCurrentPosition()` 或 `watchPosition() 時,`若獲得錯誤回呼函式,則`錯誤回呼函式的第一組參數將為 PositionError 物件:`
-
function errorCallback(error
) { alert('ERROR(' + error
.code
+ '): ' + error
.message
);};
-
+```js
+function errorCallback(error) { alert('ERROR(' + error.code + '): ' + error.message);};
+```
-
地理位置定位實際範例
+## 地理位置定位實際範例
-
HTML 內容
+### HTML 內容
-
<p><button onclick="geoFindMe()">Show my location
</button></p>
-<div id="out"></div>
+```html
+
Show my location
+
+```
-
JavaScript 內容
+### JavaScript 內容
-
function geoFindMe() {
+```js
+function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
- output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
+ output.innerHTML = "Geolocation is not supported by your browser
";
return;
}
@@ -110,10 +118,10 @@ var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_optio
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
- output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
+ output.innerHTML = 'Latitude is ' + latitude + '° Longitude is ' + longitude + '°
';
var img = new Image();
- img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
+ img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
};
@@ -122,25 +130,24 @@ var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_optio
output.innerHTML = "Unable to retrieve your location";
};
- output.innerHTML = "<p>Locating…</p>";
+ output.innerHTML = "Locating…
";
navigator.geolocation.getCurrentPosition(success, error);
}
-
+```
-
現場測試結果
+### 現場測試結果
-
若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
+若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
+{{EmbedLiveSample('地理位置定位實際範例', 350, 150)}}
-
{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}
+## 請求權限
+addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 `pref` 參數所指定的偏好中。於 `callback` 參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 `true`,則附加元件才會存取地理位置定位資料。
-
請求權限
-
-
addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 pref
參數所指定的偏好中。於 callback
參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 true
,則附加元件才會存取地理位置定位資料。
-
-
function prompt(window, pref, message, callback) {
+```js
+function prompt(window, pref, message, callback) {
let branch = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
@@ -202,26 +209,24 @@ prompt(window,
"extensions.foo-addon.allowGeolocation",
"Foo Add-on wants to know your location.",
function callback(allowed) { alert(allowed); });
-
+```
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat}}
-
Gecko 註記
+## Gecko 註記
-
Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 Mozilla 的隱私權政策 與 Google 的隱私權政策 。其內將詳述資料的使用方式。
+Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 [Mozilla 的隱私權政策](http://www.mozilla.com/en-US/legal/privacy/)與 [Google 的隱私權政策](http://www.google.com/privacy-lsf.html)。其內將詳述資料的使用方式。
-
Firefox 3.6 (Gecko 1.9.2) 新支援了 GPSD (GPS daemon) 服務,適合 Linux 的地理位置定位。
+Firefox 3.6 (Gecko 1.9.2) 新支援了 [GPSD](http://catb.org/gpsd/) (GPS daemon) 服務,適合 Linux 的地理位置定位。
-
另請參閱
+## 另請參閱
-
+- [`navigator.geolocation`](/zh-TW/docs/Web/API/window.navigator.geolocation)
+- [w3.org 的 Geolocation API](http://www.w3.org/TR/geolocation-API/)
+- [Geolocation API 相關 Demos](/en-US/demos/tag/tech:geolocation)
diff --git a/files/zh-tw/web/api/globaleventhandlers/index.md b/files/zh-tw/web/api/globaleventhandlers/index.md
index f66455648d6568..0cc311a1e9f515 100644
--- a/files/zh-tw/web/api/globaleventhandlers/index.md
+++ b/files/zh-tw/web/api/globaleventhandlers/index.md
@@ -3,217 +3,205 @@ title: GlobalEventHandlers
slug: Web/API/GlobalEventHandlers
translation_of: Web/API/GlobalEventHandlers
---
-
{{ApiRef("HTML DOM")}}
+{{ApiRef("HTML DOM")}}
-
GlobalEventHandlers(通用事件處理器)
在多個介面,如 {{domxref("HTMLElement")}}、{{domxref("Document")}} 和 {{domxref("Window")}} 當中加入了共有的事件處理器屬性,這些介面皆能夠加入除了以下清單外的更多事件處理器。
+**`GlobalEventHandlers(通用事件處理器)`**在多個介面,如 {{domxref("HTMLElement")}}、{{domxref("Document")}} 和 {{domxref("Window")}} 當中加入了共有的事件處理器屬性,這些介面皆能夠加入除了以下清單外的更多事件處理器。
-
-
Note : GlobalEventHandlers
is a mixin and not an interface; you can't actually create an object of type GlobalEventHandlers
.
-
+> **備註:** `GlobalEventHandlers` is a mixin and not an interface; you can't actually create an object of type `GlobalEventHandlers`.
-
屬性
+## 屬性
-
This interface doesn't include any properties except for the event handlers listed below.
+_This interface doesn't include any properties except for the event handlers listed below\._
-
事件處理器
+### 事件處理器
-
These event handlers are defined on the {{domxref("GlobalEventHandlers")}} mixin, and implemented by {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, as well as by {{domxref("WorkerGlobalScope")}} for Web Workers.
+These event handlers are defined on the {{domxref("GlobalEventHandlers")}} mixin, and implemented by {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, as well as by {{domxref("WorkerGlobalScope")}} for Web Workers.
-
-
- {{domxref("GlobalEventHandlers.onabort")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("abort")}} event is raised.
- {{domxref("GlobalEventHandlers.onanimationcancel")}} {{Non-standard_inline}}
- An {{event("Event_handlers", "event handler")}} called when an {{event("animationcancel")}} event is sent, indicating that a running CSS animation has been canceled.
- {{domxref("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}
- An {{event("Event_handlers", "event handler")}} called when an {{event("animationend")}} event is sent, indicating that a CSS animation has stopped playing.
- {{domxref("GlobalEventHandlers.onanimationiteration")}} {{Non-standard_inline}}
- An {{event("Event_handlers", "event handler")}} called when an {{event("animationiteration")}} event has been sent, indicating that a CSS animation has begun playing a new iteration of the animation sequence.
- {{domxref("GlobalEventHandlers.onanimationstart")}} {{Non-standard_inline}}
- An {{event("Event_handlers", "event handler")}} called when an {{event("animationstart")}} event is sent, indicating that a CSS animation has started playing.
- {{domxref("GlobalEventHandlers.onauxclick")}} {{Non-standard_inline}}
- An {{event("Event_handlers", "event handler")}} called when an {{event("auxclick")}} event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button).
- {{domxref("GlobalEventHandlers.onblur")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("blur")}} event is raised.
- {{domxref("GlobalEventHandlers.onerror")}}
- Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
- {{domxref("GlobalEventHandlers.onfocus")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("focus")}} event is raised.
- {{domxref("GlobalEventHandlers.oncancel")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("cancel")}} event is raised.
- {{domxref("GlobalEventHandlers.oncanplay")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("canplay")}} event is raised.
- {{domxref("GlobalEventHandlers.oncanplaythrough")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
- {{domxref("GlobalEventHandlers.onchange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("change")}} event is raised.
- {{domxref("GlobalEventHandlers.onclick")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("click")}} event is raised.
- {{domxref("GlobalEventHandlers.onclose")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("close")}} event is raised.
- {{domxref("GlobalEventHandlers.oncontextmenu")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
- {{domxref("GlobalEventHandlers.oncuechange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
- {{domxref("GlobalEventHandlers.ondblclick")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
- {{domxref("GlobalEventHandlers.ondrag")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("drag")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragend")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragend")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragenter")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragexit")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragleave")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragover")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragover")}} event is raised.
- {{domxref("GlobalEventHandlers.ondragstart")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
- {{domxref("GlobalEventHandlers.ondrop")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("drop")}} event is raised.
- {{domxref("GlobalEventHandlers.ondurationchange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
- {{domxref("GlobalEventHandlers.onemptied")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("emptied")}} event is raised.
- {{domxref("GlobalEventHandlers.onended")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("ended")}} event is raised.
- {{domxref("GlobalEventHandlers.ongotpointercapture")}}
-
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("gotpointercapture")}} event type is raised.
-
- {{domxref("GlobalEventHandlers.oninput")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("input")}} event is raised.
- {{domxref("GlobalEventHandlers.oninvalid")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("invalid")}} event is raised.
- {{domxref("GlobalEventHandlers.onkeydown")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keydown")}} event is raised.
- {{domxref("GlobalEventHandlers.onkeypress")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keypress")}} event is raised.
- {{domxref("GlobalEventHandlers.onkeyup")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keyup")}} event is raised.
- {{domxref("GlobalEventHandlers.onload")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("load")}} event is raised.
- {{domxref("GlobalEventHandlers.onloadeddata")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
- {{domxref("GlobalEventHandlers.onloadedmetadata")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
- {{domxref("GlobalEventHandlers.onloadend")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadend")}} event is raised (when progress has stopped on the loading of a resource.)
- {{domxref("GlobalEventHandlers.onloadstart")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadstart")}} event is raised (when progress has begun on the loading of a resource.)
- {{domxref("GlobalEventHandlers.onlostpointercapture")}}
-
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("lostpointercapture")}} event type is raised.
-
- {{domxref("GlobalEventHandlers.onmousedown")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
- {{domxref("GlobalEventHandlers.onmouseenter")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
- {{domxref("GlobalEventHandlers.onmouseleave")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
- {{domxref("GlobalEventHandlers.onmousemove")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
- {{domxref("GlobalEventHandlers.onmouseout")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
- {{domxref("GlobalEventHandlers.onmouseover")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
- {{domxref("GlobalEventHandlers.onmouseup")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
- {{domxref("GlobalEventHandlers.onmousewheel")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
- {{domxref("GlobalEventHandlers.onpause")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pause")}} event is raised.
- {{domxref("GlobalEventHandlers.onplay")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("play")}} event is raised.
- {{domxref("GlobalEventHandlers.onplaying")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("playing")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerdown")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointermove")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerup")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointercancel")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerover")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerout")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerenter")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerleave")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
- {{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
- {{domxref("GlobalEventHandlers.onprogress")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("progress")}} event is raised.
- {{domxref("GlobalEventHandlers.onratechange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
- {{domxref("GlobalEventHandlers.onreset")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("reset")}} event is raised.
- {{domxref("GlobalEventHandlers.onscroll")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("scroll")}} event is raised.
- {{domxref("GlobalEventHandlers.onseeked")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("seeked")}} event is raised.
- {{domxref("GlobalEventHandlers.onseeking")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("seeking")}} event is raised.
- {{domxref("GlobalEventHandlers.onselect")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("select")}} event is raised.
- {{domxref("GlobalEventHandlers.onselectstart")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the user starts to make a new text selection on a web page.
- {{domxref("GlobalEventHandlers.onselectionchange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the text selected on a web page changes.
- {{domxref("GlobalEventHandlers.onshow")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("show")}} event is raised.
- {{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("sort")}} event is raised.
- {{domxref("GlobalEventHandlers.onstalled")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("stalled")}} event is raised.
- {{domxref("GlobalEventHandlers.onsubmit")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("submit")}} event is raised.
- {{domxref("GlobalEventHandlers.onsuspend")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("suspend")}} event is raised.
- {{domxref("GlobalEventHandlers.ontimeupdate")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
- {{domxref("GlobalEventHandlers.onvolumechange")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
- {{domxref("GlobalEventHandlers.ontouchcancel")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchcancel")}} event is raised.
- {{domxref("GlobalEventHandlers.ontouchend")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchend")}} event is raised.
- {{domxref("GlobalEventHandlers.ontouchmove")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchmove")}} event is raised.
- {{domxref("GlobalEventHandlers.ontouchstart")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchstart")}} event is raised.
- {{domxref("GlobalEventHandlers.ontransitioncancel")}}
- An {{event("Event_handlers", "event handler")}} called when a {{event("transitioncancel")}} event is sent, indicating that a CSS transition has been cancelled.
- {{domxref("GlobalEventHandlers.ontransitionend")}}
- An {{event("Event_handlers", "event handler")}} called when a {{event("transitionend")}} event is sent, indicating that a CSS transition has finished playing.
- {{domxref("GlobalEventHandlers.onwaiting")}}
- Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("waiting")}} event is raised.
-
-
+- {{domxref("GlobalEventHandlers.onabort")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("abort")}} event is raised.
+- {{domxref("GlobalEventHandlers.onanimationcancel")}} {{Non-standard_inline}}
+ - : An {{event("Event_handlers", "event handler")}} called when an {{event("animationcancel")}} event is sent, indicating that a running [CSS animation](/docs/Web/CSS/CSS_Animations) has been canceled.
+- {{domxref("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}
+ - : An {{event("Event_handlers", "event handler")}} called when an {{event("animationend")}} event is sent, indicating that a [CSS animation](/docs/Web/CSS/CSS_Animations) has stopped playing.
+- {{domxref("GlobalEventHandlers.onanimationiteration")}} {{Non-standard_inline}}
+ - : An {{event("Event_handlers", "event handler")}} called when an {{event("animationiteration")}} event has been sent, indicating that a [CSS animation](/docs/Web/CSS/CSS_Animations) has begun playing a new iteration of the animation sequence.
+- {{domxref("GlobalEventHandlers.onanimationstart")}} {{Non-standard_inline}}
+ - : An {{event("Event_handlers", "event handler")}} called when an {{event("animationstart")}} event is sent, indicating that a [CSS animation](/docs/Web/CSS/CSS_Animations) has started playing.
+- {{domxref("GlobalEventHandlers.onauxclick")}} {{Non-standard_inline}}
+ - : An {{event("Event_handlers", "event handler")}} called when an {{event("auxclick")}} event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button).
+- {{domxref("GlobalEventHandlers.onblur")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("blur")}} event is raised.
+- {{domxref("GlobalEventHandlers.onerror")}}
+ - : Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+- {{domxref("GlobalEventHandlers.onfocus")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("focus")}} event is raised.
+- {{domxref("GlobalEventHandlers.oncancel")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+- {{domxref("GlobalEventHandlers.oncanplay")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+- {{domxref("GlobalEventHandlers.oncanplaythrough")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+- {{domxref("GlobalEventHandlers.onchange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("change")}} event is raised.
+- {{domxref("GlobalEventHandlers.onclick")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("click")}} event is raised.
+- {{domxref("GlobalEventHandlers.onclose")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("close")}} event is raised.
+- {{domxref("GlobalEventHandlers.oncontextmenu")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+- {{domxref("GlobalEventHandlers.oncuechange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondblclick")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondrag")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("drag")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragend")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragenter")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragexit")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragleave")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragover")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondragstart")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondrop")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("drop")}} event is raised.
+- {{domxref("GlobalEventHandlers.ondurationchange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+- {{domxref("GlobalEventHandlers.onemptied")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+- {{domxref("GlobalEventHandlers.onended")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("ended")}} event is raised.
+- {{domxref("GlobalEventHandlers.ongotpointercapture")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("gotpointercapture")}} event type is raised.
+- {{domxref("GlobalEventHandlers.oninput")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("input")}} event is raised.
+- {{domxref("GlobalEventHandlers.oninvalid")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+- {{domxref("GlobalEventHandlers.onkeydown")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+- {{domxref("GlobalEventHandlers.onkeypress")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+- {{domxref("GlobalEventHandlers.onkeyup")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+- {{domxref("GlobalEventHandlers.onload")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("load")}} event is raised.
+- {{domxref("GlobalEventHandlers.onloadeddata")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+- {{domxref("GlobalEventHandlers.onloadedmetadata")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+- {{domxref("GlobalEventHandlers.onloadend")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadend")}} event is raised (when progress has stopped on the loading of a resource.)
+- {{domxref("GlobalEventHandlers.onloadstart")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("loadstart")}} event is raised (when progress has begun on the loading of a resource.)
+- {{domxref("GlobalEventHandlers.onlostpointercapture")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("lostpointercapture")}} event type is raised.
+- {{domxref("GlobalEventHandlers.onmousedown")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmouseenter")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmouseleave")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmousemove")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmouseout")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmouseover")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmouseup")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+- {{domxref("GlobalEventHandlers.onmousewheel")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpause")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pause")}} event is raised.
+- {{domxref("GlobalEventHandlers.onplay")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("play")}} event is raised.
+- {{domxref("GlobalEventHandlers.onplaying")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("playing")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerdown")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointermove")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerup")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointercancel")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerover")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerout")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerenter")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerleave")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
+- {{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
+- {{domxref("GlobalEventHandlers.onprogress")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("progress")}} event is raised.
+- {{domxref("GlobalEventHandlers.onratechange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
+- {{domxref("GlobalEventHandlers.onreset")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("reset")}} event is raised.
+- {{domxref("GlobalEventHandlers.onscroll")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("scroll")}} event is raised.
+- {{domxref("GlobalEventHandlers.onseeked")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("seeked")}} event is raised.
+- {{domxref("GlobalEventHandlers.onseeking")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("seeking")}} event is raised.
+- {{domxref("GlobalEventHandlers.onselect")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("select")}} event is raised.
+- {{domxref("GlobalEventHandlers.onselectstart")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the user starts to make a new text selection on a web page.
+- {{domxref("GlobalEventHandlers.onselectionchange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the text selected on a web page changes.
+- {{domxref("GlobalEventHandlers.onshow")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("show")}} event is raised.
+- {{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("sort")}} event is raised.
+- {{domxref("GlobalEventHandlers.onstalled")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("stalled")}} event is raised.
+- {{domxref("GlobalEventHandlers.onsubmit")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("submit")}} event is raised.
+- {{domxref("GlobalEventHandlers.onsuspend")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("suspend")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontimeupdate")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
+- {{domxref("GlobalEventHandlers.onvolumechange")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontouchcancel")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchcancel")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontouchend")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchend")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontouchmove")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchmove")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontouchstart")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("touchstart")}} event is raised.
+- {{domxref("GlobalEventHandlers.ontransitioncancel")}}
+ - : An {{event("Event_handlers", "event handler")}} called when a {{event("transitioncancel")}} event is sent, indicating that a [CSS transition](/zh-TW/docs/Web/CSS/CSS_Transitions) has been cancelled.
+- {{domxref("GlobalEventHandlers.ontransitionend")}}
+ - : An {{event("Event_handlers", "event handler")}} called when a {{event("transitionend")}} event is sent, indicating that a [CSS transition](/zh-TW/docs/Web/CSS/CSS_Transitions) has finished playing.
+- {{domxref("GlobalEventHandlers.onwaiting")}}
+ - : Is an {{event("Event_handlers", "event handler")}} representing the code to be called when the {{event("waiting")}} event is raised.
-
方法
+## 方法
-
This interface defines no methods.
+_This interface defines no methods._
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.GlobalEventHandlers")}}
-
參見
+## 參見
-
- {{domxref("Element")}}
- {{event("Event_handlers", "event handler")}}
- {{domxref("Event")}}
-
+- {{domxref("Element")}}
+- {{event("Event_handlers", "event handler")}}
+- {{domxref("Event")}}
diff --git a/files/zh-tw/web/api/history/index.md b/files/zh-tw/web/api/history/index.md
index 3e012edaa63627..80dfbd5f8c443b 100644
--- a/files/zh-tw/web/api/history/index.md
+++ b/files/zh-tw/web/api/history/index.md
@@ -3,60 +3,54 @@ title: History
slug: Web/API/History
translation_of: Web/API/History
---
-
{{ APIRef("HTML DOM") }}
-
-
History
介面允許操控瀏覽器的 session history 紀錄,為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面。
-
-
屬性
-
-
The History
interface doesn't inherit any property.
-
-
- {{domxref("History.length")}} {{readOnlyInline}}
- Returns an Integer
representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1
.
- {{domxref("History.current")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
- Returns a {{domxref("DOMString")}} representing the URL of the active item of the session history. This property was never available to web content and is no more supported by any browser. Use {{domxref("Location.href")}} instead.
- {{domxref("History.next")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
- Returns a {{domxref("DOMString")}} representing the URL of the next item in the session history. This property was never available to web content and is not supported by other browsers.
- {{domxref("History.previous")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
- Returns a {{domxref("DOMString")}} representing the URL of the previous item in the session history. This property was never available to web content and is not supported by other browsers.
- {{domxref("History.scrollRestoration")}} {{experimental_inline}}
- Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either auto
or manual
.
- {{domxref("History.state")}} {{readOnlyInline}}
- Returns an any
value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{event("popstate")}} event.
-
-
-
方法
-
-
The History
interface doesn't inherit any methods.
-
-
- {{domxref("History.back()")}}
- 回到 session history 紀錄中的前一頁,等同於使用者按下瀏覽器的上一頁按鈕。相當於 history.go(-1)
。
- Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.
-
- {{domxref("History.forward()")}}
- 回到 session history 紀錄中的下一頁,等同於使用者按下瀏覽器的下一頁按鈕。相當於 history.go(1)
。
- Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.
-
- {{domxref("History.go()")}}
- 自 session history 紀錄中載入一個頁面,利用該頁面相對於目前頁面的所在位置,例如 -1 為前一頁或 1 為下一頁。若指定了一個超出範圍的值(舉例來說,在 session history 沒有先前訪頁面的情況下指定 -1),此方法將會是靜默(不會產生錯誤)且沒有任何效果的。不帶參數或是傳入 0 呼叫 go()
會重新載入目前頁面。Internet Explorer 也可以傳入字串 來前往一個於瀏覽歷史列表中指定的頁面。
- {{domxref("History.pushState()")}}
- 插入給定的資料與指定的標題(title)以及選擇性的 URL 至 session history 堆疊(stack)中。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱操控瀏覽器歷史紀錄 。
- {{domxref("History.replaceState()")}}
- 以指定的資料、標題(title)及可選的 URL 來更新歷史紀錄堆疊(history stack)中近期的項目。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱操控瀏覽器歷史紀錄 。
-
-
-
規範
+{{ APIRef("HTML DOM") }}
+
+**`History`** 介面允許操控瀏覽器的 _session history_ 紀錄,為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面。
+
+## 屬性
+
+_The `History`_ _interface doesn't inherit any property._
+
+- {{domxref("History.length")}} {{readOnlyInline}}
+ - : Returns an `Integer` representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns `1`.
+- {{domxref("History.current")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
+ - : Returns a {{domxref("DOMString")}} representing the URL of the active item of the session history. This property was never available to web content and is no more supported by any browser. Use {{domxref("Location.href")}} instead.
+- {{domxref("History.next")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
+ - : Returns a {{domxref("DOMString")}} representing the URL of the next item in the session history. This property was never available to web content and is not supported by other browsers.
+- {{domxref("History.previous")}} {{readOnlyInline}} {{ non-standard_inline() }} {{Deprecated_Inline}}
+ - : Returns a {{domxref("DOMString")}} representing the URL of the previous item in the session history. This property was never available to web content and is not supported by other browsers.
+- {{domxref("History.scrollRestoration")}} {{experimental_inline}}
+ - : Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either `auto` or `manual`.
+- {{domxref("History.state")}} {{readOnlyInline}}
+ - : Returns an `any` value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{event("popstate")}} event.
+
+## 方法
+
+_The `History`_ _interface doesn't inherit any methods._
+
+- {{domxref("History.back()")}}
+ - : 回到 session history 紀錄中的前一頁,等同於使用者按下瀏覽器的上一頁按鈕。相當於 `history.go(-1)`。
+
+ > **備註:** Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.
+- {{domxref("History.forward()")}}
+ - : 回到 session history 紀錄中的下一頁,等同於使用者按下瀏覽器的下一頁按鈕。相當於 `history.go(1)`。
+
+ > **備註:** Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.
+- {{domxref("History.go()")}}
+ - : 自 session history 紀錄中載入一個頁面,利用該頁面相對於目前頁面的所在位置,例如 -1 為前一頁或 1 為下一頁。若指定了一個超出範圍的值(舉例來說,在 session history 沒有先前訪頁面的情況下指定 -1),此方法將會是靜默(不會產生錯誤)且沒有任何效果的。不帶參數或是傳入 0 呼叫 `go()` 會重新載入目前頁面。Internet Explorer [也可以傳入字串](
)來前往一個於瀏覽歷史列表中指定的頁面。
+- {{domxref("History.pushState()")}}
+ - : 插入給定的資料與指定的標題(title)以及選擇性的 URL 至 session history 堆疊(stack)中。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱[操控瀏覽器歷史紀錄](/zh-TW/docs/Web/API/History_API)。
+- {{domxref("History.replaceState()")}}
+ - : 以指定的資料、標題(title)及可選的 URL 來更新歷史紀錄堆疊(history stack)中近期的項目。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱[操控瀏覽器歷史紀錄](/zh-TW/docs/Web/API/History_API)。
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.History")}}
-參見
+## 參見
-
- The {{domxref("Window.history")}} property returning the history of the current session.
-
+- The {{domxref("Window.history")}} property returning the history of the current session.
diff --git a/files/zh-tw/web/api/history_api/index.md b/files/zh-tw/web/api/history_api/index.md
index b5e6f4a8a75106..0799bf324d9bd4 100644
--- a/files/zh-tw/web/api/history_api/index.md
+++ b/files/zh-tw/web/api/history_api/index.md
@@ -7,152 +7,152 @@ tags:
- History
translation_of: Web/API/History_API
---
-DOM {{ domxref("window") }} 物件透過 {{ domxref("window.history", "history") }} 物件,提供了進入瀏覽歷史的方式。他透過一些方便的屬性與方法,讓你可以在歷史紀錄中往上一步或往下一步移動,並且讓你——從 HTML5 開始——能操作歷史紀錄堆疊(history stack)的內容。
+DOM {{ domxref("window") }} 物件透過 {{ domxref("window.history", "history") }} 物件,提供了進入瀏覽歷史的方式。他透過一些方便的屬性與方法,讓你可以在歷史紀錄中往上一步或往下一步移動,並且讓你——從 HTML5 開始——能操作歷史紀錄堆疊(history stack)的內容。
-在歷史紀錄中移動
+## 在歷史紀錄中移動
-往前往後歷史紀錄可以用 back()
, forward()
, 和 go()
的方法。
+往前往後歷史紀錄可以用 `back()`, `forward()`, 和 `go()` 的方法。
-往前往後
+### 往前往後
-要在歷史紀錄中往上一步移動,可以:
+要在歷史紀錄中往上一步移動,可以:
-window.history.back();
-
+```js
+window.history.back();
+```
-這完全等同於用戶在瀏覽器上點選「上一頁」按鈕。
+這完全等同於用戶在瀏覽器上點選「上一頁」按鈕。
-同樣的,你也可以往下一步移動(等同於用戶點擊往後一頁的按鈕):
+同樣的,你也可以往下一步移動(等同於用戶點擊往後一頁的按鈕):
-window.history.forward();
-
+```js
+window.history.forward();
+```
-移動到特定的歷史紀錄
+### 移動到特定的歷史紀錄
-你可以用 go()
方法來從頁面的 session history 紀錄中載入特定紀錄,以目前頁面的相對位置而定(目前的頁面想當然爾是 index 0)。
+你可以用 `go()` 方法來從頁面的 session history 紀錄中載入特定紀錄,以目前頁面的相對位置而定(目前的頁面想當然爾是 index 0)。
-往前一頁(等同於呼叫 back()
):
+往前一頁(等同於呼叫 `back()`):
-window.history.go(-1);
-
+```js
+window.history.go(-1);
+```
-往後一頁(等同於呼叫 forward()
):
+往後一頁(等同於呼叫 `forward()`):
-window.history.go(1);
-
+```js
+window.history.go(1);
+```
-同樣的你也可以傳入 2,讓頁面直往後兩頁,依此類推。
+同樣的你也可以傳入 2,讓頁面直往後兩頁,依此類推。
-你可以查看 length 這個屬性來取得目前瀏覽歷史的總數我:
+你可以查看 length 這個屬性來取得目前瀏覽歷史的總數我:
-var numberOfEntries = window.history.length;
-
+```js
+var numberOfEntries = window.history.length;
+```
-備註: Internet Explorer 支援在 go()
中以 URL 的值作為參數;這不在標準中,Gecko 也不支援。
+> **備註:** Internet Explorer 支援在 `go()` 中以 URL 的值作為參數;這不在標準中,Gecko 也不支援。
-加入和修改歷史紀錄
+## 加入和修改歷史紀錄
-HTML5 加入了 history.pushState()
和 history.replaceState()
方法,讓你可以加入或修改歷史紀錄。這些方法都可以跟 {{ domxref("window.onpopstate") }} 事件一同應用。
+HTML5 加入了 [`history.pushState()`](/zh-TW/docs/Web/API/History/pushState) 和 [`history.replaceState()`]() 方法,讓你可以加入或修改歷史紀錄。這些方法都可以跟 {{ domxref("window.onpopstate") }} 事件一同應用。
-使用 history.pushState()
後,會改變 XMLHttpRequest
時 HTTP 標頭中 referrer 的值。referrer 會是創造 XMLHttpRequest
物件時的當前視窗文件(this
)的 URL。
+使用 `history.pushState()`後,會改變 [`XMLHttpRequest`](/zh-TW/docs/Web/API/XMLHttpRequest) 時 HTTP 標頭中 referrer 的值。referrer 會是創造 [`XMLHttpRequest`](/zh-TW/docs/Web/API/XMLHttpRequest) 物件時的當前視窗文件(`this`)的 URL。
-pushState() 方法範例
+### pushState() 方法範例
-假設 http://mozilla.org/foo.html 執行了下面的 JavaScript:
+假設 http\://mozilla.org/foo.html 執行了下面的 JavaScript:
-var stateObj = { foo: "bar" };
+```js
+var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
-
+```
-這會讓網址列顯示 http://mozilla.org/bar.html,但不會讓瀏覽器去載入 bar.html
,甚或去檢查 bar.html
存在與否。
+這會讓網址列顯示 http\://mozilla.org/bar.html,但不會讓瀏覽器去載入 `bar.html`,甚或去檢查 `bar.html` 存在與否。
-假設現在使用者瀏覽到 http://google.com,然後點擊上一頁鈕。這時網址列會顯示 http://mozilla.org/bar.html,頁面會獲得 popstate
的事件(state object 會包含一份 stateObj
的副件)。頁面長得跟 foo.html
很像,但是可能在 popstate
事件執行中被修改。
+假設現在使用者瀏覽到 http\://google.com,然後點擊上一頁鈕。這時網址列會顯示 http\://mozilla.org/bar.html,頁面會獲得 `popstate` 的事件(_state object_ 會包含一份 `stateObj` 的副件)。頁面長得跟 `foo.html` 很像,但是可能在 `popstate` 事件執行中被修改。
-如果我再點一次上一頁鈕, 網址會改變成為 http://mozilla.org/foo.html,且文件會得到另外一個 popstate
事件,此次會包含一個 null state object。同樣的,回上頁鈕不會改變文件的內容,只是文件可能會在 popstate
事件中被手動更新。
+如果我再點一次上一頁鈕, 網址會改變成為 http\://mozilla.org/foo.html,且文件會得到另外一個 `popstate` 事件,此次會包含一個 null state object。同樣的,回上頁鈕不會改變文件的內容,只是文件可能會在 `popstate` 事件中被手動更新。
-pushState() 方法
+### pushState() 方法
-pushState()
取用三個參數:一個 state 物件、title(目前忽略)與 URL(可選用)。我們來看看三個參數的細節之處:
+`pushState()` 取用三個參數:一個 state 物件、title(目前忽略)與 URL(可選用)。我們來看看三個參數的細節之處:
-
-
- state object ——state object 是與 pushState()
建立的新瀏覽歷史紀錄有關的一個 JavaScript 物件。只要使用者到了新的 state ,一個 popstate
的事件就會被觸發,然後該事件的 state
屬性會包含一個複製的歷史紀錄的 state object。
+- **state object**——state object 是與 `pushState()` 建立的新瀏覽歷史紀錄有關的一個 JavaScript 物件。只要使用者到了新的 state ,一個 `popstate` 的事件就會被觸發,然後該事件的 `state` 屬性會包含一個複製的歷史紀錄的 state object。
- state 物件可以是任何可序列化的東西。因為 Firefox 儲存 state 物件到使用者的硬碟,當瀏覽器被重新啟動的時候,他們是可以被恢復的,因此我們加上了 640k 個字元的長度限制在一個以序列化表示的 state object。如果你傳送一個比這個更大的序列化表示的 state object 到 pushState()
,這個方法會丟出一個例外事件。如果你需要更多空間的話,你可以試著用 sessionStorage
和/或 localStorage
。
-
-
- title ——Firefox 目前忽略了這個參數,雖然他以後有可能會採用。如果以後改變了這個作法,傳送空白的字串應該還會是安全的。另外,你可以傳送一個短的標題來敘述你想要到的 state。
-
-
- URL ——這個新歷史紀錄的 URL 從這個參數做設定。值得注意的是,在 pushState()
被呼叫之後,瀏覽器並不會馬上嘗試載入這個 URL ,但是它可能在以後嘗試載入這個 URL ,例如使用者重新開啟瀏覽器之後。新的 URL 不一定需要為一個絕對的路徑;如果是相對路徑,會依據目前的URL來解析。新的 URL 需要與目前 URL 的 origin 是一樣的;否則,pushState() 會丟出一個錯誤的例外。這個參數是選擇性的;如果沒有被指定的話,他會設定為目前文件的 URL。
-
-
+ state 物件可以是任何可序列化的東西。因為 Firefox 儲存 state 物件到使用者的硬碟,當瀏覽器被重新啟動的時候,他們是可以被恢復的,因此我們加上了 640k 個字元的長度限制在一個以序列化表示的 state object。如果你傳送一個比這個更大的序列化表示的 state object 到 `pushState()`,這個方法會丟出一個例外事件。如果你需要更多空間的話,你可以試著用 `sessionStorage` 和/或 `localStorage`。
-備註: 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始,這個物件是以
the structured clone algorithm 序列化。這會允許更多種不同的物件可以被安全的傳送。
+- **title**——Firefox 目前忽略了這個參數,雖然他以後有可能會採用。如果以後改變了這個作法,傳送空白的字串應該還會是安全的。另外,你可以傳送一個短的標題來敘述你想要到的 state。
+- **URL**——這個新歷史紀錄的 URL 從這個參數做設定。值得注意的是,在 `pushState()` 被呼叫之後,瀏覽器並不會馬上嘗試載入這個 URL ,但是它可能在以後嘗試載入這個 URL ,例如使用者重新開啟瀏覽器之後。新的 URL 不一定需要為一個絕對的路徑;如果是相對路徑,會依據目前的 URL 來解析。新的 URL 需要與目前 URL 的 origin 是一樣的;否則,pushState() 會丟出一個錯誤的例外。這個參數是選擇性的;如果沒有被指定的話,他會設定為目前文件的 URL。
-從某種意義上,呼叫 pushState()
與設定 window.location = "#foo"
是類似的,兩個都會去建立和啟用另一個和目前文件有關的歷史紀錄。但是 pushState()
有一些優勢:
+> **備註:** 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始,這個物件是以 [the structured clone algorithm](/zh-TW/DOM/The_structured_clone_algorithm) 序列化。這會允許更多種不同的物件可以被安全的傳送。
-
- 新的 URL 可以是任何一個與目前的 URL 在同一個 origin 的 URL。相對來說,只有你設定 window.location
只修改 hash 時,才讓你保持在同一個 {{ domxref("document") }} 。
- 如果你不想要的話,你可以不必去改變 URL 。相對來說,設定 window.location = "#foo";
只有在目前的 hash 不是 #foo
的時候,會建立一個新的歷史紀錄。
- 你可以將任意的資料與你的新的歷史紀錄做關聯。用 hash-based 的方法,你需要將所有相關的資料編碼成一個短字串。
- If title
is subsequently used by browsers, this data can be utilized (independent of, say, the hash).
-
+從某種意義上,呼叫 `pushState()` 與設定 `window.location = "#foo"` 是類似的,兩個都會去建立和啟用另一個和目前文件有關的歷史紀錄。但是 `pushState()` 有一些優勢:
-注意 pushState()
永遠不會造成一個 hashchange
事件被觸發,即使新的 URL 和舊的 URL 的不同處只有 hash 的部份也不會。
+- 新的 URL 可以是任何一個與目前的 URL 在同一個 origin 的 URL。相對來說,只有你設定 `window.location` 只修改 hash 時,才讓你保持在同一個 {{ domxref("document") }} 。
+- 如果你不想要的話,你可以不必去改變 URL 。相對來說,設定 `window.location = "#foo";` 只有在目前的 hash 不是 `#foo` 的時候,會建立一個新的歷史紀錄。
+- 你可以將任意的資料與你的新的歷史紀錄做關聯。用 hash-based 的方法,你需要將所有相關的資料編碼成一個短字串。
+- If `title `is subsequently used by browsers, this data can be utilized (independent of, say, the hash).
-In a XUL document, it creates the specified XUL element.
+注意 `pushState()` 永遠不會造成一個 `hashchange` 事件被觸發,即使新的 URL 和舊的 URL 的不同處只有 hash 的部份也不會。
-In other documents, it creates an element with a null
namespace URI.
+In a [XUL](/zh-TW/docs/Mozilla/Tech/XUL) document, it creates the specified XUL element.
-replaceState() 方法
+In other documents, it creates an element with a `null` namespace URI.
-history.replaceState()
的執行就像 history.pushState()
,除了 replaceState()
是修改目前的歷史紀錄而不是創造一個新的。
+### replaceState() 方法
-replaceState()
很實用的時機是當你要更新目前歷史紀錄的 state object 或是URL來反應一些使用者的動作時。
+`history.replaceState()` 的執行就像 `history.pushState()` ,除了 `replaceState() `是修改目前的歷史紀錄而不是創造一個新的。
-備註: 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始, 這個物件是以
the structured clone algorithm 序列化。這會允許更多種不同的物件可以被安全的傳送。
+`replaceState() `很實用的時機是當你要更新目前歷史紀錄的 state object 或是 URL 來反應一些使用者的動作時。
-replaceState() 方法範例
+> **備註:** 在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始, 這個物件是以 [the structured clone algorithm](/zh-TW/DOM/The_structured_clone_algorithm) 序列化。這會允許更多種不同的物件可以被安全的傳送。
-Suppose http://mozilla.org/foo.html executes the following JavaScript:
+### replaceState() 方法範例
-var stateObj = { foo: "bar" };
+Suppose http\://mozilla.org/foo.html executes the following JavaScript:
+
+```js
+var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
-
+```
-The explanation of these two lines above can be found at "Example of pushState() method" section. Then suppose http://mozilla.org/bar.html executes the following JavaScript:
+The explanation of these two lines above can be found at "Example of pushState() method" section. Then suppose http\://mozilla.org/bar.html executes the following JavaScript:
-history.replaceState(stateObj, "page 3", "bar2.html");
-
+```js
+history.replaceState(stateObj, "page 3", "bar2.html");
+```
-This will cause the URL bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html
or even check that bar2.html
exists.
+This will cause the URL bar to display http\://mozilla.org/bar2.html, but won't cause the browser to load `bar2.html` or even check that `bar2.html` exists.
-Suppose now that the user now navigates to http://www.microsoft.com, then clicks back. At this point, the URL bar will display http://mozilla.org/bar2.html. If the user now clicks back again, the URL bar will display http://mozilla.org/foo.html, and totaly bypass bar.html.
+Suppose now that the user now navigates to http\://www\.microsoft.com, then clicks back. At this point, the URL bar will display http\://mozilla.org/bar2.html. If the user now clicks back again, the URL bar will display http\://mozilla.org/foo.html, and totaly bypass bar.html.
-popstate 事件
+### popstate 事件
-每次 active 的歷史紀錄被更動的時候,一個 popstate
事件會被發送到目前的 window。如果被啟用的歷史紀錄是由於呼叫 pushState
建立的或是呼叫 replaceState
所影響的,這個 popstate
事件的 state
屬性會含有一個歷史紀錄的 state object 的副本。
+每次 active 的歷史紀錄被更動的時候,一個 `popstate` 事件會被發送到目前的 window。如果被啟用的歷史紀錄是由於呼叫 `pushState` 建立的或是呼叫 `replaceState` 所影響的,這個 `popstate` 事件的 `state` 屬性會含有一個歷史紀錄的 state object 的副本。
-使用範例參閱 {{ domxref("window.onpopstate") }}。
+使用範例參閱 {{ domxref("window.onpopstate") }}。
-讀取目前的 state
+### 讀取目前的 state
-當你讀取頁面的時候,可能會有 non-null state 的物件。這會發生在,例如說,如果設定一個 state 物件(用 pushState()
或是 replaceState()
),然後使用者重新啟動他的瀏覽器。當重新讀取你的頁面的時候,頁面會得到一個 onload
事件,但是沒有 popstate
事件。然而,如果你讀取了 history.state
屬性,你會得到像是 popstate
被觸發時,你會得到的 state object 。
+當你讀取頁面的時候,可能會有 non-null state 的物件。這會發生在,例如說,如果設定一個 state 物件(用 `pushState()` 或是 `replaceState()`),然後使用者重新啟動他的瀏覽器。當重新讀取你的頁面的時候,頁面會得到一個 `onload` 事件,但是沒有 `popstate` 事件。然而,如果你讀取了 `history.state` 屬性,你會得到像是 `popstate` 被觸發時,你會得到的 state object 。
-像這樣使用 history.state
屬性,你可以讀取目前的歷史紀錄的狀態
而不需要等待一個 popstate
事件:
+像這樣使用 `history.state` 屬性,你可以讀取目前的歷史紀錄的`狀態`而不需要等待一個 `popstate` 事件:
-var currentState = history.state;
-
+```js
+var currentState = history.state;
+```
-範例
+## 範例
-完整的 AJAX 網站範例 ,請參閱:Ajax navigation example 。
+完整的 AJAX 網站範例 ,請參閱:[Ajax navigation example](/zh-TW/docs/DOM/Manipulating_the_browser_history/Example)。
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.History")}}
diff --git a/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.md b/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.md
index 9bda3af7d66bd3..69175d50fefdeb 100644
--- a/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.md
+++ b/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.md
@@ -3,103 +3,109 @@ title: 拖曳操作
slug: Web/API/HTML_Drag_and_Drop_API/Drag_operations
translation_of: Web/API/HTML_Drag_and_Drop_API/Drag_operations
---
-{{DefaultAPISidebar("HTML Drag and Drop API")}}
+{{DefaultAPISidebar("HTML Drag and Drop API")}}
-本文會一一說明拖曳各步驟的作業。
+本文會一一說明拖曳各步驟的作業。
-The drag operations described in this document use the {{domxref("DataTransfer")}} interface. This document does not use the {{domxref("DataTransferItem")}} interface nor the {{domxref("DataTransferItemList")}} interface.
+The drag operations described in this document use the {{domxref("DataTransfer")}} interface. This document does _not_ use the {{domxref("DataTransferItem")}} interface nor the {{domxref("DataTransferItemList")}} interface.
-Draggable 屬性
+## Draggable 屬性
-網頁中有些預設的拖曳行為,例如文字選擇、圖片或超連結,當拖曳圖片或超連結時,圖片或超連結的 URL 會被當作拖曳作業中所攜帶的資料,而其他類型元素則必須另外處理才能拖曳,試試看選擇網頁某一部分,然後按住滑鼠鍵來進行拖曳,依據OS不同,或許會有一些跟著滑鼠移動的效果,但這僅僅只是預設效果行為,實際上沒有任何資料跟著被拖曳。
+網頁中有些預設的拖曳行為,例如文字選擇、圖片或超連結,當拖曳圖片或超連結時,圖片或超連結的 URL 會被當作拖曳作業中所攜帶的資料,而其他類型元素則必須另外處理才能拖曳,試試看選擇網頁某一部分,然後按住滑鼠鍵來進行拖曳,依據 OS 不同,或許會有一些跟著滑鼠移動的效果,但這僅僅只是預設效果行為,實際上沒有任何資料跟著被拖曳。
-In HTML, apart from the default behavior for images, links, and selections, no other elements are draggable by default. In XUL , all elements are draggable.
+In HTML, apart from the default behavior for images, links, and selections, no other elements are draggable by default. In [XUL](/zh-TW/docs/Mozilla/Tech/XUL), all elements are draggable.
-除了文字選擇、圖片或超連結之外,沒有元素預設是可拖曳的。所以要讓一個元素可以拖曳,有幾件事必須要做:
+除了文字選擇、圖片或超連結之外,沒有元素預設是可拖曳的。所以要讓一個元素可以拖曳,有幾件事必須要做:
-
- 在想要拖曳的元素上設定 {{htmlattrxref("draggable")}}
屬性為 true
。
- 註冊 {{event("dragstart")}}
事件之事件處理器。
- {{domxref("DataTransfer.setData","Set the drag data")}} within the listener defined above.
-
+- 在想要拖曳的元素上設定 `{{htmlattrxref("draggable")}}` 屬性為 `true`。
+- 註冊 `{{event("dragstart")}}` 事件之事件處理器。
+- {{domxref("DataTransfer.setData","Set the drag data")}} within the listener defined above.
-以下是一段簡單的範例。
+以下是一段簡單的範例。
-<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
- This text <strong>may</strong> be dragged.
-</div>
-
+```html
+
+ This text may be dragged.
+
+```
-draggable 為 true後,該 DIV 元素便可以拖曳,反之,倘若 draggable 為 false 或無設定則不可拖曳,只有其中下含的文字可以被選擇。draggable 屬性適用於任何元素,一般來說預設為false,除了圖片和連結預設為 true,所以說如果想要阻止圖片和連結被拖曳,則可以設定draggable 為 false。
+draggable 為 true 後,該 DIV 元素便可以拖曳,反之,倘若 draggable 為 false 或無設定則不可拖曳,只有其中下含的文字可以被選擇。draggable 屬性適用於任何元素,一般來說預設為 false,除了圖片和連結預設為 true,所以說如果想要阻止圖片和連結被拖曳,則可以設定 draggable 為 false。
-請注意,一旦元素被定為可拖曳之後,其下內含的文字或其他元素便無法像平常一樣用滑鼠選擇,使用者之能夠改用鍵盤或按住 Alt 鍵搭配滑鼠進行選擇。
+請注意,一旦元素被定為可拖曳之後,其下內含的文字或其他元素便無法像平常一樣用滑鼠選擇,使用者之能夠改用鍵盤或按住 Alt 鍵搭配滑鼠進行選擇。
-至於 XUL 元素則是預設皆可拖曳。
+至於 XUL 元素則是預設皆可拖曳。
-<button label="Drag Me" ondragstart="event.dataTransfer.setData('text/plain', 'Drag Me Button');">
-
+```html
+
+```
-開始拖曳
+## 開始拖曳
-下方範例在dragstart註冊一個事件處理器。
+下方範例在 dragstart 註冊一個事件處理器。
-<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
- This text <strong>may</strong> be dragged.
-</div>
-
+```html
+
+ This text may be dragged.
+
+```
-當拖曳作業開始,dragstart 事件會觸發,然後我們可以在事件處理器中準備好我們所要攜帶的資料、想要的拖曳回饋效果,不過基本上其實只需要準備資料就好,因為預設拖曳回饋效果已經足以應付大多數的狀況,此外,我們也可以改在上一層父元素註冊事件處理器,因為拖曳事件會上向傳遞 ( Bubble up ) 。
+當拖曳作業開始,dragstart 事件會觸發,然後我們可以在事件處理器中準備好我們所要攜帶的資料、想要的拖曳回饋效果,不過基本上其實只需要準備資料就好,因為預設拖曳回饋效果已經足以應付大多數的狀況,此外,我們也可以改在上一層父元素註冊事件處理器,因為拖曳事件會上向傳遞 ( Bubble up ) 。
-拖曳資料
+## 拖曳資料
-所有的拖曳事件物件都有一個 dataTransfer 屬性,這個屬性是用來攜帶資料。
+所有的拖曳事件物件都有一個 [dataTransfer](/zh-TW/docs/DragDrop/DataTransfer) 屬性,這個屬性是用來攜帶資料。
-當拖曳時,資料必須和被拖曳目標作連結,比如說拖曳文字框中反白選擇的文字,那麼文字本身便是連結資料,同理,拖曳連結時URL便是連結資料。
+當拖曳時,資料必須和被拖曳目標作連結,比如說拖曳文字框中反白選擇的文字,那麼文字本身便是連結資料,同理,拖曳連結時 URL 便是連結資料。
-資料包含兩個部分,一是資料型態(或格式)、二是資料值。所謂資料型態是用文字描述資料型態(如text/plain 代表文字資料),而資料值則是文字,要加入拖曳資料需要提供資料的型態和內容值;有了資料後,我們可以在dragenter或dragover事件處理器中,透過檢查資料型態來決定是否可以接受後續的放置操作,比如說只接受連結類資料的拖曳目標區(drop target),會檢查資料型態是否為text/uri-list 。
+資料包含兩個部分,一是資料型態(或格式)、二是資料值。所謂資料型態是用文字描述資料型態(如[text/plain](/zh-TW/docs/DragDrop/Recommended_Drag_Types#text)代表文字資料),而資料值則是文字,要加入拖曳資料需要提供資料的型態和內容值;有了資料後,我們可以在 dragenter 或 dragover 事件處理器中,透過檢查資料型態來決定是否可以接受後續的放置操作,比如說只接受連結類資料的拖曳目標區(drop target),會檢查資料型態是否為[text/uri-list](/zh-TW/docs/DragDrop/Recommended_Drag_Types#link)。
-資料型態符合MIME型態,如text/plain 或image/jpeg 等等,而我們自己也可以自定義其他型態,最常使用的型態請見推薦拖曳資料型態 。
+資料型態符合 MIME 型態,如[text/plain](/zh-TW/docs/DragDrop/Recommended_Drag_Types#text)或[image/jpeg](/zh-TW/docs/DragDrop/Recommended_Drag_Types#image)等等,而我們自己也可以自定義其他型態,最常使用的型態請見[推薦拖曳資料型態](/zh-TW/docs/DragDrop/Recommended_Drag_Types)。
-一趟拖曳作業中可以攜帶多個多種型態的資料,所以我們可以自定義自己的型態同時,還提供其他資料給不認得自定義資料型態的其他拖曳目標區使用。通常最通用的資料會是文字類型資料。
+一趟拖曳作業中可以攜帶多個多種型態的資料,所以我們可以自定義自己的型態同時,還提供其他資料給不認得自定義資料型態的其他拖曳目標區使用。通常最通用的資料會是文字類型資料。
-呼叫setData 方法,傳入資料型態和資料,這樣就可以攜帶想要的資料了:
+呼叫[setData](/zh-TW/docs/DragDrop/DataTransfer#setData.28.29)方法,傳入資料型態和資料,這樣就可以攜帶想要的資料了:
-event.dataTransfer.setData("text/plain", "Text to drag");
-
+```js
+event.dataTransfer.setData("text/plain", "Text to drag");
+```
-上例資料是”Text to drag”文字,型態是text/plain。
+上例資料是”Text to drag”文字,型態是 text/plain。
-呼叫多次setData我們就可以攜帶多種資料。
+呼叫多次 setData 我們就可以攜帶多種資料。
-var dt = event.dataTransfer;
+```js
+var dt = event.dataTransfer;
dt.setData("application/x-bookmark", bookmarkString);
dt.setData("text/uri-list", "http://www.mozilla.org");
dt.setData("text/plain", "http://www.mozilla.org");
-
+```
-這裡加入了三種資料,第一種是自定義的”application/x-bookmark”,雖然有更豐富的內容可使用,但只有我們自己認識,而另外我們又為其他網站或應用加入了兩種比較常見的資料,”text/uri-list”以及”text/plain”。
+這裡加入了三種資料,第一種是自定義的”application/x-bookmark”,雖然有更豐富的內容可使用,但只有我們自己認識,而另外我們又為其他網站或應用加入了兩種比較常見的資料,”text/uri-list”以及”text/plain”。
-如果對同一種資料型態加入兩次資料,則新加資料會取代舊資料。
+如果對同一種資料型態加入兩次資料,則新加資料會取代舊資料。
-呼叫clearData 會清除資料。
+呼叫[clearData](/zh-TW/docs/DragDrop/DataTransfer#clearData.28.29)會清除資料。
-event.dataTransfer.clearData("text/uri-list");
-
+```js
+event.dataTransfer.clearData("text/uri-list");
+```
-如果呼叫clearData時有傳入資料型態,則只會清除該型態資料,如果沒有傳入任何型態,則所有資料皆會被清除。
+如果呼叫 clearData 時有傳入資料型態,則只會清除該型態資料,如果沒有傳入任何型態,則所有資料皆會被清除。
-設定拖曳圖片
+## 設定拖曳圖片
-當拖曳進行中,以拖曳元素為基礎,一個半透明的圖片會自動產生出來,並且跟著滑鼠移動。如果想要,我們也可以呼叫setDragImage()來指定我們自己的拖曳使用圖片。
+當拖曳進行中,以拖曳元素為基礎,一個半透明的圖片會自動產生出來,並且跟著滑鼠移動。如果想要,我們也可以呼叫[`setDragImage()來指定我們自己的拖曳使用圖片。`](/en-US/docs/DragDrop/DataTransfer#setDragImage.28.29)
-event.dataTransfer.setDragImage(image, xOffset, yOffset);
-
+```js
+event.dataTransfer.setDragImage(image, xOffset, yOffset);
+```
-setDragImage需要三個參數,一是圖片來源(通常是圖片元素,但也可以是canvas元素或其他元素),拖曳使用圖片會依照圖片來源在螢幕上所顯示的樣子產生;二和三是圖片相對於滑鼠指標的位置位移量。
+setDragImage 需要三個參數,一是圖片來源(通常是圖片元素,但也可以是 canvas 元素或其他元素),拖曳使用圖片會依照圖片來源在螢幕上所顯示的樣子產生;二和三是圖片相對於滑鼠指標的位置位移量。
-不過也是能夠使用文件外部的圖片或canvas元素,當需要透過canvas元素產生客製圖片時,這個技巧很有用,如下範例所示:
+不過也是能夠使用文件外部的圖片或 canvas 元素,當需要透過 canvas 元素產生客製圖片時,這個技巧很有用,如下範例所示:
-function dragWithCustomImage(event) {
+```js
+function dragWithCustomImage(event) {
var canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas");
canvas.width = canvas.height = 50;
@@ -115,159 +121,171 @@ dt.setData("text/plain", "http://www.mozilla.org");
dt.setData('text/plain', 'Data to Drag');
dt.setDragImage(canvas, 25, 25);
}
-
+```
-上面我們的canvas是50 x 50px大小,然後我們位移一半25讓圖片落在滑鼠指標中央。
+上面我們的 canvas 是 50 x 50px 大小,然後我們位移一半 25 讓圖片落在滑鼠指標中央。
-在Gecko上開發,比如說外掛或Mozllia應用程式,Gecko9.0{{geckoRelease("9.0")}}支援使用{{XULElem("panel")}}元素作為拖曳圖片,簡單將XUL panel元素傳入setDragImage方法即可。
+在 Gecko 上開發,比如說外掛或 Mozllia 應用程式,Gecko9.0{{geckoRelease("9.0")}}支援使用{{XULElem("panel")}}元素作為拖曳圖片,簡單將 XUL panel 元素傳入 setDragImage 方法即可。
-試想下面這個 {{XULElem("panel")}}元素:
+試想下面這個 {{XULElem("panel")}}元素:
-<panel id="panel" style="opacity: 0.6">
- <description id="pb">Drag Me</description>
-</panel>
+```xml
+
+ Drag Me
+
-<vbox align="start" style="border: 1px solid black;" ondragstart="startDrag(event)">
- <description>Drag Me</description>
-</vbox>
-
+
+ Drag Me
+
+```
-當使用者拖曳{{XULElem("vbox")}} 元素時,startDrag函數會被呼叫。
+當使用者拖曳{{XULElem("vbox")}} 元素時,startDrag 函數會被呼叫。
-function startDrag(event) {
- event.dataTransfer.setData("text/plain", "<strong>Body</strong>");
+```js
+function startDrag(event) {
+ event.dataTransfer.setData("text/plain", "Body ");
event.dataTransfer.setDragImage(document.getElementById("panel"), 20, 20);
}
-
+```
-我們用HTML格式的"<strong>Body</strong>"作為資料,然後用pnael元素作為圖片。
+我們用 HTML 格式的"\Body\ "作為資料,然後用 pnael 元素作為圖片。
-拖曳效果
+## 拖曳效果
-拖曳作業有好機種;copy作業代表被拖曳資料會被複製一份到拖曳目標區,move作業代表移動被拖曳的資料,link作業代表拖曳來源區和拖曳目標區有某種關係。
+拖曳作業有好機種;copy 作業代表被拖曳資料會被複製一份到拖曳目標區,move 作業代表移動被拖曳的資料,link 作業代表拖曳來源區和拖曳目標區有某種關係。
-在dragstart事件中可以設定effectAllowed 屬性,指定拖曳源頭允許的作業。
+在 dragstart 事件中可以設定[effectAllowed](/zh-TW/docs/DragDrop/DataTransfer#effectAllowed.28.29)屬性,指定拖曳源頭允許的作業。
-event.dataTransfer.effectAllowed = "copy";
-
+```js
+event.dataTransfer.effectAllowed = "copy";
+```
-上面只有copy被允許,但還有其他種類:
+上面只有 copy 被允許,但還有其他種類:
- 只能移動或連結。
+只能移動或連結。
-
- none
- 不允許任何作業。
- copy
- 只能複製。
- move
- 只能移動。
- link
- 只有連結。
- copyMove
- 只能複製或移動。
- copyLink
- 只能複製或連結。
- linkMove
- all
- 複製、移動或連結皆可。
-
+- none
+ - : 不允許任何作業。
+- copy
+ - : 只能複製。
+- move
+ - : 只能移動。
+- link
+ - : 只有連結。
+- copyMove
+ - : 只能複製或移動。
+- copyLink
+ - : 只能複製或連結。
+- linkMove
-effectAllowed 屬性預設所有作業都接受,如all值。
+ all
-在dragenter或dragover事件中,我們可以藉由檢查effectAllowed來知道那些作業是被允許的,另外,另一個相關聯的dropEffect 屬性應該要是effectAllowed的其中一個作業,但是dropEffect不接受多重作業,只可以是none, copy, move和link。
+ - : 複製、移動或連結皆可。
-dropEffect屬性會在在dragenter以及dragover事件中初始化為使用者想要執行的作業效果,使用者能夠透過按鍵(依平台不同,通常是Shift或Ctrl鍵),在複製、移動、連接作業之間切換,同時滑鼠指標也會跟著相應變換,例如複製作業的滑鼠旁會多出一個+的符號。
+[effectAllowed](/zh-TW/docs/DragDrop/DataTransfer#effectAllowed.28.29) 屬性預設所有作業都接受,如 all 值。
-effectAllowed和dropEffect屬性可以在dragenter或dragover事件中更改,更改effectAllowed屬性能讓拖曳作業只能在支援被允許作業類型的拖曳目標上執行,好比說effectAllowed為copyMove的作業就會阻止使用者進行link類型的作業。
+在 dragenter 或 dragover 事件中,我們可以藉由檢查 effectAllowed 來知道那些作業是被允許的,另外,另一個相關聯的[dropEffect](/zh-TW/docs/DragDrop/DataTransfer#dropEffect.28.29)屬性應該要是 effectAllowed 的其中一個作業,但是 dropEffect 不接受多重作業,只可以是 none, copy, move 和 link。
-我們也可以更改dropEffect來強迫使用者執行某項作業,而且應該要是effectAllowed所列舉的作業。
+dropEffect 屬性會在在 dragenter 以及 dragover 事件中初始化為使用者想要執行的作業效果,使用者能夠透過按鍵(依平台不同,通常是 Shift 或 Ctrl 鍵),在複製、移動、連接作業之間切換,同時滑鼠指標也會跟著相應變換,例如複製作業的滑鼠旁會多出一個+的符號。
-event.dataTransfer.effectAllowed = "copyMove";
+effectAllowed 和 dropEffect 屬性可以在 dragenter 或 dragover 事件中更改,更改 effectAllowed 屬性能讓拖曳作業只能在支援被允許作業類型的拖曳目標上執行,好比說 effectAllowed 為 copyMove 的作業就會阻止使用者進行 link 類型的作業。
+
+我們也可以更改 dropEffect 來強迫使用者執行某項作業,而且應該要是 effectAllowed 所列舉的作業。
+
+```js
+event.dataTransfer.effectAllowed = "copyMove";
event.dataTransfer.dropEffect = "copy";
-
+```
-上面的範例中copy就是會被執行的作業效果。
+上面的範例中 copy 就是會被執行的作業效果。
-若effectAllowed或dropEffect為none,那麼沒有放置作業可以被執行。
+若 effectAllowed 或 dropEffect 為 none,那麼沒有放置作業可以被執行。
-指定拖曳目標
+## 指定拖曳目標
-dragenter和dragover事件就是用來指定拖曳目標區,也就是放置資料的目標區,絕大多數的元素預設的事件都不准放置資料。
+dragenter 和 dragover 事件就是用來指定拖曳目標區,也就是放置資料的目標區,絕大多數的元素預設的事件都不准放置資料。
-所以想要放置資料到元素上,就必須取消預設事件行為。取消預設事件行為能夠藉由回傳false或呼叫event.preventDefault 方法。
+所以想要放置資料到元素上,就必須取消預設事件行為。取消預設事件行為能夠藉由回傳 false 或呼叫[event.preventDefault](/zh-TW/docs/DOM/event.preventDefault)方法。
-<div ondragover="return false">
-<div ondragover="event.preventDefault()">
-
+```html
+
+
+```
-
通常我們只有在適當的時機點才需要呼叫event.preventDefault方法、取消預設事件行為,比如說被拖曳進來的是連結。所以檢查被拖曳進來的物件,當符合條件後再來取消預設事件行為。
+通常我們只有在適當的時機點才需要呼叫 event.preventDefault 方法、取消預設事件行為,比如說被拖曳進來的是連結。所以檢查被拖曳進來的物件,當符合條件後再來取消預設事件行為。
-
藉由檢查拖曳資料型態來決定是否允許放置,是最常見的作法。dataTransfer物件的types 屬性是一個拖曳資料型態的列表,其中順序按照資料被加入之先後排序。
+藉由檢查拖曳資料型態來決定是否允許放置,是最常見的作法。dataTransfer 物件的[types](/zh-TW/docs/DragDrop/DataTransfer#types.28.29)屬性是一個拖曳資料型態的列表,其中順序按照資料被加入之先後排序。
-
function doDragOver(event)
+```js
+function doDragOver(event)
{
var isLink = event.dataTransfer.types.contains("text/uri-list");
if (isLink)
event.preventDefault();
}
-
+```
-
上面我們呼叫contains方法檢察text/uri-list是否存在拖曳資料型態的列表之內,有的話才取消預設行為、准許放置作業,否則,不取消預設行為、不准許放置作業。
+上面我們呼叫 contains 方法檢察 text/uri-list 是否存在拖曳資料型態的列表之內,有的話才取消預設行為、准許放置作業,否則,不取消預設行為、不准許放置作業。
-
檢查拖曳資料型態後,我們也可以依此更動effectAllowed和dropEffect屬性,只不過,如果沒有取消預設行為,更動並不會有甚麼影響。
+檢查拖曳資料型態後,我們也可以依此更動 effectAllowed 和 dropEffect 屬性,只不過,如果沒有取消預設行為,更動並不會有甚麼影響。
-
Updates to DataTransfer.types
+### Updates to DataTransfer.types
-
Note that the latest spec now dictates that {{domxref("DataTransfer.types")}} should return a frozen array of {{domxref("DOMString")}}s rather than a {{domxref("DOMStringList")}} (this is supported in Firefox 52 and above).
+Note that the latest spec now dictates that {{domxref("DataTransfer.types")}} should return a frozen array of {{domxref("DOMString")}}s rather than a {{domxref("DOMStringList")}} (this is supported in Firefox 52 and above).
-
As a result, the contains method no longer works on the property; the includes method should be used instead to check if a specific type of data is provided, using code like the following:
+As a result, the [contains](/zh-TW/docs/Web/API/Node/contains) method no longer works on the property; the [includes](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method should be used instead to check if a specific type of data is provided, using code like the following:
-
if ([...event.dataTransfer.types].includes('text/html')) {
+```js
+if ([...event.dataTransfer.types].includes('text/html')) {
// Do something
-}
+}
+```
-
You could always use some feature detection to determine which method is supported on types
, and run code as appropriate.
+You could always use some feature detection to determine which method is supported on `types`, and run code as appropriate.
-
放置回饋
+## 放置回饋
-
有好幾種方法回饋使用者,告訴使用者甚麼元素可以接受放置作業,最簡單的是滑鼠會指標會自動變換樣式(視平台而定)。
+有好幾種方法回饋使用者,告訴使用者甚麼元素可以接受放置作業,最簡單的是滑鼠會指標會自動變換樣式(視平台而定)。
-
滑鼠指標提示雖然夠用了,不過有時我們還是會想做其他UI上的樣式變化。-moz-drag-over的CSS pseudo-class便可以應用在拖曳目標元素上。
+滑鼠指標提示雖然夠用了,不過有時我們還是會想做其他 UI 上的樣式變化。-moz-drag-over 的 CSS pseudo-class 便可以應用在拖曳目標元素上。
-
.droparea:-moz-drag-over {
+```css
+.droparea:-moz-drag-over {
border: 1px solid black;
}
-
+```
-
當目標元素的dragenter預設事件有被取消時,這個pseudo-class就會啟動,目標UI會套用1px的黑色border,請注意dragover並不會檢查這項設定。
+當目標元素的 dragenter 預設事件有被取消時,這個 pseudo-class 就會啟動,目標 UI 會套用 1px 的黑色 border,請注意 dragover 並不會檢查這項設定。
-
其他比如說插入圖片等,在dragenter事件內執行更多更複雜的樣式變化也是可以的。
+其他比如說插入圖片等,在 dragenter 事件內執行更多更複雜的樣式變化也是可以的。
-
倘若想要做出圖片更著滑鼠在拖曳目標區上面移動的效果,那麼可以在dragover事件內來取得的clientX 和clientY 的滑鼠座標資訊。
+倘若想要做出圖片更著滑鼠在拖曳目標區上面移動的效果,那麼可以在 dragover 事件內來取得的[clientX](/zh-TW/docs/DOM/event.clientX)和[clientY](/zh-TW/docs/DOM/event.clientY)的滑鼠座標資訊。
-
最後,應該要在dragleave事件內復原之前所做樣式變更,dragleave事件不需要取消預設事件行為、永遠都會觸發,即使拖曳被取消了;至於使用-moz-drag-over的CSS方法的話,樣式復原會自動執行,不用擔心。
+最後,應該要在 dragleave 事件內復原之前所做樣式變更,dragleave 事件不需要取消預設事件行為、永遠都會觸發,即使拖曳被取消了;至於使用-moz-drag-over 的 CSS 方法的話,樣式復原會自動執行,不用擔心。
-
執行放置作業
+## 執行放置作業
-
當使用者在拖曳目標區上放開滑鼠時,drop事件就會觸發。當drop事件發生,我們需要取出被丟入的資料,然後處理之。
+當使用者在拖曳目標區上放開滑鼠時,drop 事件就會觸發。當 drop 事件發生,我們需要取出被丟入的資料,然後處理之。
-
要取出被丟入的資料,那就要呼叫dataTransfer物件的getData 方法。getData方法接受資料型態的參數,它會回傳setData 所存入的對應資料型態的資料,倘若沒有對應型態資料,那空字串就會被回傳。
+要取出被丟入的資料,那就要呼叫 dataTransfer 物件的[getData](/zh-TW/docs/DragDrop/DataTransfer#getData.28.29)方法。getData 方法接受資料型態的參數,它會回傳[setData](/zh-TW/docs/DragDrop/DataTransfer#setData.28.29)所存入的對應資料型態的資料,倘若沒有對應型態資料,那空字串就會被回傳。
-
function onDrop(event)
+```js
+function onDrop(event)
{
var data = event.dataTransfer.getData("text/plain");
event.target.textContent = data;
event.preventDefault();
-}
+}
+```
-
上面的範例會取出文字資料,假設拖曳目標區是文字區域,例如p或div元素,那麼資料就會被當作文字內容,插入目標元素之中。
+上面的範例會取出文字資料,假設拖曳目標區是文字區域,例如 p 或 div 元素,那麼資料就會被當作文字內容,插入目標元素之中。
-
網頁之中,如果我們已經處理過放置資料,那應該要呼叫{preventDefault}方法防止瀏覽器再次處理資料,比如說,Firefox預設是會開啟拖入的連結,但我們可以取消這項預設行為來避免開啟連結。
+網頁之中,如果我們已經處理過放置資料,那應該要呼叫{preventDefault}方法防止瀏覽器再次處理資料,比如說,Firefox 預設是會開啟拖入的連結,但我們可以取消這項預設行為來避免開啟連結。
-
當然也可以取得其他種類資料來使用,比如說連結資料,text/uri-list 。
+當然也可以取得其他種類資料來使用,比如說連結資料,[text/uri-list](/zh-TW/docs/DragDrop/Recommended_Drag_Types#link)。
-
function doDrop(event)
+```js
+function doDrop(event)
{
var links = event.dataTransfer.getData("text/uri-list").split("\n");
for each (var link in links) {
@@ -281,20 +299,22 @@ event.dataTransfer.dropEffect = "copy";
}
event.preventDefault();
}
-
+```
-
上面的範例取得連結資料,然後生成連結元素、加入頁面。從text/uri-list字面上不難猜出這種資料是一行行的URL,所以我們呼叫split 方法拆開一行行的URL,再將URL一個一個加入頁面。請注意我們有避開開頭為”#”字元的註解。
+上面的範例取得連結資料,然後生成連結元素、加入頁面。從 text/uri-list 字面上不難猜出這種資料是一行行的 URL,所以我們呼叫[split](/zh-TW/docs/JavaScript/Reference/Global_Objects/String/split)方法拆開一行行的 URL,再將 URL 一個一個加入頁面。請注意我們有避開開頭為”#”字元的註解。
-
更簡單的作法是採用特別URL型態。URL型態是一個特殊簡寫用途形態,它不會出現在{types}屬性中,但它可以方便的取得第一個連結,如下:
+更簡單的作法是採用特別 URL 型態。URL 型態是一個特殊簡寫用途形態,它不會出現在{types}屬性中,但它可以方便的取得第一個連結,如下:
-
var link = event.dataTransfer.getData("URL");
-
+```js
+var link = event.dataTransfer.getData("URL");
+```
-
這個作法能夠省去檢查註解和一個一個掃過URL,但只會得到第一個URL。
+這個作法能夠省去檢查註解和一個一個掃過 URL,但只會得到第一個 URL。
-
下面的例子會從多個支援的資料型態中,找出支援的資料。
+下面的例子會從多個支援的資料型態中,找出支援的資料。
-
function doDrop(event)
+```js
+function doDrop(event)
{
var types = event.dataTransfer.types;
var supportedTypes = ["application/x-moz-file", "text/uri-list", "text/plain"];
@@ -302,25 +322,24 @@ event.dataTransfer.dropEffect = "copy";
if (types.length)
var data = event.dataTransfer.getData(types[0]);
event.preventDefault();
-}
+}
+```
-
完成拖曳
+## 完成拖曳
-
拖曳作業完成後,不論成功或取消於否,被拖曳元素的dragend
事件都會觸發,如果想要判別作業是否完成,可以檢查dropEffect屬性,若是dropEffect為none,代表拖曳作業被取消,否則dropEffect的值代表所完成的作業類型。
+拖曳作業完成後,不論成功或取消於否,被拖曳元素的[`dragend`](/en-US/docs/Web/Reference/Events/dragend)事件都會觸發,如果想要判別作業是否完成,可以檢查 dropEffect 屬性,若是 dropEffect 為 none,代表拖曳作業被取消,否則 dropEffect 的值代表所完成的作業類型。
-
有一個Gecko專屬的mozUserCancelled 屬性,當使用者按ESC鍵取消拖曳後,這個屬性會為true,但若是因其他理由被取消或成功,則為false
+有一個 Gecko 專屬的[mozUserCancelled](/zh-TW/docs/DragDrop/DataTransfer#mozUserCancelled.28.29)屬性,當使用者按 ESC 鍵取消拖曳後,這個屬性會為 true,但若是因其他理由被取消或成功,則為 false
-
拖曳作業的放置可以發生在同一個視窗或其他應用程式,而且dragend事件還是會觸發,不過事件中的screenX 與screenY 屬性會是放置發生點的資訊。
+拖曳作業的放置可以發生在同一個視窗或其他應用程式,而且 dragend 事件還是會觸發,不過事件中的[screenX](/zh-TW/docs/DOM/event.screenX)與[screenY](/zh-TW/docs/DOM/event.screenY)屬性會是放置發生點的資訊。
-
當dragend事件結束傳遞後,拖曳作業也完成了。
+當 dragend 事件結束傳遞後,拖曳作業也完成了。
-
[1] 在Gecko,如果被拖曳元素在拖曳作業還在進行中移動或刪除,那麼dragend事件就不會觸發。bug 460801
+\[1] 在 Gecko,如果被拖曳元素在拖曳作業還在進行中移動或刪除,那麼 dragend 事件就不會觸發。[bug 460801](https://bugzilla.mozilla.org/show_bug.cgi?id=460801)
-
參見
+## 參見
-
+- [HTML Drag and Drop API (Overview)](/Web/API/HTML_Drag_and_Drop_API)
+- [Dragging and Dropping Multiple Items](/Web/Guide/HTML/Dragging_and_Dropping_Multiple_Items)
+- [Recommended Drag Types](/Web/Guide/HTML/Recommended_Drag_Types)
+- [HTML5 Living Standard: Drag and Drop](https://html.spec.whatwg.org/multipage/interaction.html#dnd)
diff --git a/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.md b/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.md
index b216919d0dcfc2..546a5c8fec296c 100644
--- a/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.md
+++ b/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.md
@@ -6,74 +6,73 @@ tags:
- Canvas
translation_of: Web/API/HTMLCanvasElement/toDataURL
---
-
-
-
{{APIRef("Canvas API")}}
-
-
+{{APIRef("Canvas API")}}
-
HTMLCanvasElement.toDataURL()
方法回傳含有圖像和參數設置特定格式的 data URIs (預設 PNG ). 回傳的圖像解析度為 96 dpi.
+**`HTMLCanvasElement.toDataURL()`** 方法回傳含有圖像和參數設置特定格式的 [data URIs](/zh-TW/docs/Web/HTTP/data_URIs) (預設 [PNG](https://en.wikipedia.org/wiki/Portable_Network_Graphics)). 回傳的圖像解析度為 96 dpi.
-
- 如果 canvas 的高度或是寬度為 0
, 將會回傳字串 "data:,"
.
- 如果要求的圖像類型並非 image/png
, 但是回傳的類型卻是 data:image/png
, 表示要求的圖像類型並不支援.
- Chrome 也支援 image/webp
類型.
-
+- 如果 canvas 的高度或是寬度為 `0`, 將會回傳字串 `"data:,"`.
+- 如果要求的圖像類型並非 `image/png`, 但是回傳的類型卻是 `data:image/png`, 表示要求的圖像類型並不支援.
+- Chrome 也支援 `image/webp` 類型.
-
表達式
+## 表達式
-
canvas .toDataURL(type , encoderOptions );
-
+```plain
+canvas.toDataURL(type, encoderOptions);
+```
-
參數
+### 參數
-
- type
{{optional_inline}}
- 圖像格式的 {{domxref("DOMString")}}. 預設為 image/png
.
- encoderOptions
{{optional_inline}}
- 表示 image/jpeg 或是 image/webp 的圖像品質, 為0
到 1
之間的 {{jsxref("Number")}}.
- 如果值不在上述範圍中, 將會使用預設值. 其他的會忽略.
-
+- `type` {{optional_inline}}
+ - : 圖像格式的 {{domxref("DOMString")}}. 預設為 `image/png`.
+- `encoderOptions` {{optional_inline}}
+ - : `表示 image/jpeg 或是 image/webp 的圖像品質, 為0` 到 `1` 之間的 {{jsxref("Number")}}.
+ 如果值不在上述範圍中, 將會使用預設值. 其他的會忽略.
-
回傳值
+### 回傳值
-
包含 data URI 的 {{domxref("DOMString")}}.
+包含 [data URI](/zh-TW/docs/Web/HTTP/data_URIs) 的 {{domxref("DOMString")}}.
-
範例
+## 範例
-
創建 {{HTMLElement("canvas")}} 元素:
+創建 {{HTMLElement("canvas")}} 元素:
-
<canvas id="canvas" width="5" height="5"></canvas>
-
+```html
+
+```
-
可以使用下面的方式獲取 data-URL:
+可以使用下面的方式獲取 data-URL:
-
var canvas = document.getElementById("canvas");
+```js
+var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
-
+```
-
設置圖像的品質
+### 設置圖像的品質
-
var fullQuality = canvas.toDataURL("image/jpeg", 1.0);
+```js
+var fullQuality = canvas.toDataURL("image/jpeg", 1.0);
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
var mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
var lowQuality = canvas.toDataURL("image/jpeg", 0.1);
-
+```
-
範例: 動態改變圖像
+### 範例: 動態改變圖像
-
為了動態改變圖像, 可以與滑鼠事件一起使用 (gray-scale versus color in this example):
+為了動態改變圖像, 可以與滑鼠事件一起使用 (gray-scale versus color in this example):
-
HTML
+#### HTML
-
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
+```html
+
+```
-
JavaScript
+#### JavaScript
-
window.addEventListener("load", removeColors);
+```js
+window.addEventListener("load", removeColors);
function showColorImg() {
this.style.display = "none";
@@ -90,7 +89,7 @@ function removeColors() {
nImgsLen = aImages.length,
oCanvas = document.createElement("canvas"),
oCtx = oCanvas.getContext("2d");
- for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
+ for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
oColorImg = aImages[nImgId];
nWidth = oColorImg.offsetWidth;
nHeight = oColorImg.offsetHeight;
@@ -100,7 +99,7 @@ function removeColors() {
oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
aPix = oImgData.data;
nPixLen = aPix.length;
- for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
+ for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
}
oCtx.putImageData(oImgData, 0, 0);
@@ -112,19 +111,18 @@ function removeColors() {
oColorImg.style.display = "none";
oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
}
-}
+}
+```
-
規範
+## 規範
{{Specifications}}
-
瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.HTMLCanvasElement.toDataURL")}}
-
參見
+## 參見
-
- The interface defining it, {{domxref("HTMLCanvasElement")}}.
- Data URIs in the HTTP reference.
-
+- The interface defining it, {{domxref("HTMLCanvasElement")}}.
+- [Data URIs](/zh-TW/docs/Web/HTTP/data_URIs) in the [HTTP](/zh-TW/docs/Web/HTTP) reference.
diff --git a/files/zh-tw/web/api/htmlcollection/index.md b/files/zh-tw/web/api/htmlcollection/index.md
index 3295f6d629b4db..c0ee49f0d41853 100644
--- a/files/zh-tw/web/api/htmlcollection/index.md
+++ b/files/zh-tw/web/api/htmlcollection/index.md
@@ -3,37 +3,34 @@ title: HTMLCollection
slug: Web/API/HTMLCollection
translation_of: Web/API/HTMLCollection
---
-
{{APIRef("HTML DOM")}}
+{{APIRef("HTML DOM")}}
-
HTMLCollection
介面表示了一種成員為 {{domxref("Element")}} 物件的通用集合(如 arguments 一般的類陣列,成員順序同元素在文件中的順序),並提供了可用來選取集合成員的方法與屬性。
+**`HTMLCollection`** 介面表示了一種成員為 {{domxref("Element")}} 物件的通用集合(如 [arguments](/zh-TW/docs/Web/JavaScript/Reference/Functions/arguments) 一般的類陣列,成員順序同元素在文件中的順序),並提供了可用來選取集合成員的方法與屬性。
-
Note: This interface is called HTMLCollection
for historical reasons (before DOM4, collections implementing this interface could only have HTML elements as their items).
+> **備註:** This interface is called `HTMLCollection` for historical reasons (before DOM4, collections implementing this interface could only have HTML elements as their items).
-
HTMLCollection
物件對 HTML DOM 而言具有即時性(live),如果底層的文件(document
物件)發生改變,HTMLCollection
物件會自動更新至最新的狀態。
+`HTMLCollection` 物件對 HTML DOM 而言具有即時性(live),如果底層的文件(`document` 物件)發生改變,`HTMLCollection` 物件會自動更新至最新的狀態。
-
屬性
+## 屬性
-
- {{domxref("HTMLCollection.length")}} {{readonlyInline}}
- Returns the number of items in the collection.
-
+- {{domxref("HTMLCollection.length")}} {{readonlyInline}}
+ - : Returns the number of items in the collection.
-
方法
+## 方法
-
- {{domxref("HTMLCollection.item()")}}
- Returns the specific node at the given zero-based index
into the list. Returns null
if the index
is out of range.
- {{domxref("HTMLCollection.namedItem()")}}
- Returns the specific node whose ID or, as a fallback, name matches the string specified by name
. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name
attribute. Returns null
if no node exists by the given name.
-
+- {{domxref("HTMLCollection.item()")}}
+ - : Returns the specific node at the given zero-based `index` into the list. Returns `null` if the `index` is out of range.
+- {{domxref("HTMLCollection.namedItem()")}}
+ - : Returns the specific node whose ID or, as a fallback, name matches the string specified by `name`. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the `name` attribute. Returns `null` if no node exists by the given name.
-
Usage in JavaScript
+## Usage in JavaScript
-
HTMLCollection also
exposes its members directly as properties by both name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these.
+`HTMLCollection also` exposes its members directly as properties by both name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these.
-
For example, assuming there is one <form>
element in the document and its id
is "myForm"
:
+For example, assuming there is one `
` element in the document and its `id` is `"myForm"`:
-var elem1, elem2;
+```js
+var elem1, elem2;
// document.forms is an HTMLCollection
@@ -47,19 +44,18 @@ elem2 = document.forms.namedItem("myForm");
alert(elem1 === elem2); // shows: "true"
-elem1 = document.forms["named.item.with.periods"];
+elem1 = document.forms["named.item.with.periods"];
+```
-瀏覽器相容性
+## 瀏覽器相容性
-Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem
's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection
and Opera returns a {{domxref("NodeList")}} of all matching elements.
+Different browsers behave differently when there are more than one elements matching the string used as an index (or `namedItem`'s argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another `HTMLCollection` and Opera returns a {{domxref("NodeList")}} of all matching elements.
-規範
+## 規範
{{Specifications}}
-參見
+## 參見
-
- {{domxref("NodeList")}}
- {{domxref("HTMLFormControlsCollection")}}, {{domxref("HTMLOptionsCollection")}}
-
+- {{domxref("NodeList")}}
+- {{domxref("HTMLFormControlsCollection")}}, {{domxref("HTMLOptionsCollection")}}
diff --git a/files/zh-tw/web/api/htmlinputelement/index.md b/files/zh-tw/web/api/htmlinputelement/index.md
index c1d4a24eab814e..a347d0c38af5c6 100644
--- a/files/zh-tw/web/api/htmlinputelement/index.md
+++ b/files/zh-tw/web/api/htmlinputelement/index.md
@@ -3,349 +3,208 @@ title: HTMLInputElement
slug: Web/API/HTMLInputElement
translation_of: Web/API/HTMLInputElement
---
-{{ APIRef("HTML DOM") }}
-
-HTMLInputElement
介面提供了特殊的屬性及方法以操作 input
元素的顯示與佈局。
-
-{{InheritanceDiagram(600,120)}}
-
-屬性
-
-
- Properties related to the parent form
-
-
-
-
- form
{{readonlyInline}}
- {{domxref("HTMLFormElement")}} object:
Returns a reference to the parent form element.
-
-
- formAction
- string
: Returns / Sets the element's {{ htmlattrxref("formaction", "input") }} attribute, containing the URI of a program that processes information submitted by the element. This overrides the {{ htmlattrxref("action", "form") }} attribute of the parent form.
-
-
- formEncType
- string
: Returns / Sets the element's {{ htmlattrxref("formenctype", "input") }} attribute, containing the type of content that is used to submit the form to the server. This overrides the {{ htmlattrxref("enctype", "form") }} attribute of the parent form.
-
-
- formMethod
- string
: Returns / Sets the element's {{ htmlattrxref("formmethod", "input") }} attribute, containing the HTTP method that the browser uses to submit the form. This overrides the {{ htmlattrxref("method", "form") }} attribute of the parent form.
-
-
- formNoValidate
- boolean
: Returns / Sets the element's {{ htmlattrxref("formnovalidate", "input") }} attribute, indicating that the form is not to be validated when it is submitted. This overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the parent form.
-
-
- formTarget
- string
: Returns / Sets the element's {{ htmlattrxref("formtarget", "input") }} attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the {{ htmlattrxref("target", "form") }} attribute of the parent form.
-
-
-
-
-
- Properties that apply to any type of input element that is not hidden
-
-
- name
- string
: Returns / Sets the element's {{ htmlattrxref("name", "input") }} attribute, containing a name that identifies the element when submitting the form.
-
-
- type
- string:
Returns / Sets the element's {{ htmlattrxref("type", "input") }} attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.
-
-
- disabled
- boolean
: Returns / Sets the element's {{ htmlattrxref("disabled", "input") }} attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }}
-
-
- autofocus
- boolean:
Returns / Sets the element's {{ htmlattrxref("autofocus", "input") }} attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to hidden
(that is, you cannot automatically set focus to a hidden control).
-
-
- required
- boolean
: Returns / Sets the element's {{ htmlattrxref("required", "input") }} attribute, indicating that the user must fill in a value before submitting a form.
-
-
- value
- string:
Returns / Sets the current value of the control.
- Note: If the user enters a value different from the value expected, this may return an empty string.
-
-
-
- validity
{{readonlyInline}}
- {{domxref("ValidityState")}} object:
Returns the validity state that this element is in.
-
-
- validationMessage
{{readonlyInline}}
- string:
Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ({{htmlattrxref("willValidate","input")}} is false), or it satisfies its constraints.
-
-
- willValidate
{{readonlyInline}}
- {{jsxref("Boolean")}}:
Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
-
-
-
+{{ APIRef("HTML DOM") }}
+
+**`HTMLInputElement`** 介面提供了特殊的屬性及方法以操作 `input` 元素的顯示與佈局。
+
+{{InheritanceDiagram(600,120)}}
+
+## 屬性
+
+| `form `{{readonlyInline}} | _`{{domxref("HTMLFormElement")}} object:`_ Returns a reference to the parent form element. |
+| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `formAction` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("formaction", "input") }} attribute, containing the URI of a program that processes information submitted by the element. This overrides the {{ htmlattrxref("action", "form") }} attribute of the parent form. |
+| `formEncType` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("formenctype", "input") }} attribute, containing the type of content that is used to submit the form to the server. This overrides the {{ htmlattrxref("enctype", "form") }} attribute of the parent form. |
+| `formMethod` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("formmethod", "input") }} attribute, containing the HTTP method that the browser uses to submit the form. This overrides the {{ htmlattrxref("method", "form") }} attribute of the parent form. |
+| `formNoValidate` | _`boolean`:_ Returns / Sets the element's {{ htmlattrxref("formnovalidate", "input") }} attribute, indicating that the form is not to be validated when it is submitted. This overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the parent form. |
+| `formTarget` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("formtarget", "input") }} attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the {{ htmlattrxref("target", "form") }} attribute of the parent form. |
+
+| `name` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("name", "input") }} attribute, containing a name that identifies the element when submitting the form. |
+| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `type` | `string:` Returns / Sets the element's {{ htmlattrxref("type", "input") }} attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values. |
+| `disabled` | _`boolean`:_ Returns / Sets the element's {{ htmlattrxref("disabled", "input") }} attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }} |
+| `autofocus` | `boolean:` Returns / Sets the element's {{ htmlattrxref("autofocus", "input") }} attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to `hidden` (that is, you cannot automatically set focus to a hidden control). |
+| `required` | _`boolean`:_ Returns / Sets the element's {{ htmlattrxref("required", "input") }} attribute, indicating that the user must fill in a value before submitting a form. |
+| `value` | `string:` Returns / Sets the current value of the control.**Note:** If the user enters a value different from the value expected, this may return an empty string. |
+| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity state that this element is in. |
+| `validationMessage` {{readonlyInline}} | `string:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ({{htmlattrxref("willValidate","input")}} is false), or it satisfies its constraints. |
+| `willValidate `{{readonlyInline}} | _`{{jsxref("Boolean")}}:`_ Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. |
+
+| `checked` | `boolean: `Returns / Sets the current state of the element when {{htmlattrxref("type","input")}} is `checkbox` or `radio`. |
+| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
+| `defaultChecked` | _`boolean:`_ Returns / Sets the default state of a radio button or checkbox as originally specified in HTML that created this object. |
+| `indeterminate` | `boolean:` indicates that the checkbox is neither on nor off. |
+
+| `alt` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("alt", "input") }} attribute, containing alternative text to use when {{htmlattrxref("type","input")}} is `image.` |
+| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `height` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("height", "input") }} attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is `image`. |
+| `src` | `string:` Returns / Sets the element's {{ htmlattrxref("src", "input") }} attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is `image`; otherwise it is ignored. |
+| `width` | `string:` Returns / Sets the document's {{ htmlattrxref("width", "input") }} attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is `image`. |
+
+| `accept` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("accept", "input") }} attribute, containing comma-separated list of file types accepted by the server when {{htmlattrxref("type","input")}} is `file`. |
+| ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `allowdirs` {{non-standard_inline}} | boolean: Part of the non-standard Directory Upload API; indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. |
+| {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}} | boolean: Returns the {{htmlattrxref("webkitdirectory", "input")}} attribute; if true, the file system picker interface only accepts directories instead of files. |
+| {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}} | Array of {{domxref("FileSystemEntry")}} objects describing the currently-selected files or directories. |
+
+| `autocomplete` | _`string`:_ Returns / Sets the element's {{htmlattrxref("autocomplete", "input")}} attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is `hidden`, `checkbox`, `radio`, `file`, or a button type (`button`, `submit`, `reset`, `image`). Possible values are: "on": the browser can autocomplete the value using previously stored value "off": the user must explicity enter a value |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `maxLength` | _`long`:_ Returns / Sets the element's {{ htmlattrxref("maxlength", "input") }} attribute, containing the **maximum length of characters** (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) |
+| `size` | _`unsigned long`:_ Returns / Sets the element's {{ htmlattrxref("size", "input") }} attribute, containing **size of the control**. This value is in pixels unless the value of {{htmlattrxref("type","input")}} is `text` or `password`, in which case, it is an integer number of characters. Applies only when {{htmlattrxref("type","input")}} is set to `text`, `search`, `tel`, `url`, `email`, or `password`; otherwise it is ignored. |
+| `pattern` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("pattern", "input") }} attribute, containing a **regular expression** that the control's value is checked against. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. |
+| `placeholder` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("placeholder", "input") }} attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. |
+| `readOnly` | _`boolean`:_ Returns / Sets the element's {{ htmlattrxref("readonly", "input") }} attribute, indicating that the user cannot modify the value of the control. This is ignored if the value of the {{htmlattrxref("type","input")}} attribute is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type. |
+| `min` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("min", "input") }} attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value. |
+| `max` | _`string`:_ Returns / Sets the element's {{ htmlattrxref("max", "input") }} attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (**min** attribute) value. |
+| `selectionStart` | _`unsigned long`:_ Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element. |
+| `selectionEnd` | _`unsigned long`:_ Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position. |
+| `selectionDirection` | _`string`:_ Returns / Sets the direction in which selection occurred. Possible values are: `"forward"` if selection was performed in the start-to-end direction of the current locale, `"backward"` for the opposite direction, `"none"` if the direction is unknown." |
- Properties that apply only to elements of type "checkbox" or "radio"
-
-
- checked
- boolean:
Returns / Sets the current state of the element when {{htmlattrxref("type","input")}} is checkbox
or radio
.
-
-
- defaultChecked
- boolean:
Returns / Sets the default state of a radio button or checkbox as originally specified in HTML that created this object.
-
-
- indeterminate
- boolean:
indicates that the checkbox is neither on nor off.
-
-
+
+ Properties not yet categorized
+
+
+
+ defaultValue
+
+ string:
Returns / Sets the default value as
+ originally specified in the HTML that created this object.
+
+
+
+ dirName
+
+ string:
Returns / Sets the directionality of the
+ element.
+
+
+
+ accessKey
+
+ string
: Returns a string containing a single
+ character that switches input focus to the control when pressed.
+
+
+
+ list
{{readonlyInline}}
+
+ {{domxref("HTMLElement")}} object:
+ Returns the element pointed by the
+ {{ htmlattrxref("list", "input") }} attribute. The property
+ may be null
if no HTML element found in the same tree.
+
+
+
+ multiple
+
+ boolean
: Returns / Sets the element's
+ {{ htmlattrxref("multiple", "input") }} attribute,
+ indicating whether more than one value is possible (e.g., multiple
+ files).
+
+
+
+ files
{{readonlyInline}}
+
+ {{domxref("FileList")}} array:
Returns
+ the list of selected files.
+
+
+
+ labels
{{readonlyInline}}
+
+ {{domxref("NodeList")}} array:
Returns a
+ list of {{ HTMLElement("label") }} elements that are labels
+ for this element.
+
+
+
+ step
+
+ string:
Returns / Sets the element's
+ {{ htmlattrxref("step", "input") }} attribute, which works
+ with {{htmlattrxref("min","input")}} and
+ {{htmlattrxref("max","input")}} to limit the increments at
+ which a numeric or date-time value can be set. It can be the string
+ any
or a positive floating point number. If this is not set
+ to any
, the control accepts only values at multiples of the
+ step value greater than the minimum.
+
+
+
+ valueAsDate
+
+ {{jsxref("Date")}} object:
Returns / Sets
+ the value of the element, interpreted as a date, or null
if
+ conversion is not possible.
+
+
+
+ valueAsNumber
+
+ double
: Returns the value of the element, interpreted as
+ one of the following, in order:
+
+ a time value
+ a number
+ NaN if conversion is impossible
+
+
+
+
+ autocapitalize
{{experimental_inline}}
+
+ string:
defines the capitalization behavior for
+ user input. Valid values are none
, off
,
+ characters
, words
, or sentences
.
+
+
+
-
- Properties that apply only to elements of type "image"
-
-
- alt
- string
: Returns / Sets the element's {{ htmlattrxref("alt", "input") }} attribute, containing alternative text to use when {{htmlattrxref("type","input")}} is image.
-
-
- height
- string
: Returns / Sets the element's {{ htmlattrxref("height", "input") }} attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image
.
-
-
- src
- string:
Returns / Sets the element's {{ htmlattrxref("src", "input") }} attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is image
; otherwise it is ignored.
-
-
- width
- string:
Returns / Sets the document's {{ htmlattrxref("width", "input") }} attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image
.
-
-
-
-
-
- Properties that apply only to elements of type "file"
-
-
- accept
- string
: Returns / Sets the element's {{ htmlattrxref("accept", "input") }} attribute, containing comma-separated list of file types accepted by the server when {{htmlattrxref("type","input")}} is file
.
-
-
- allowdirs
{{non-standard_inline}}
- boolean: Part of the non-standard Directory Upload API; indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference.
-
-
- {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}}
- boolean: Returns the {{htmlattrxref("webkitdirectory", "input")}} attribute; if true, the file system picker interface only accepts directories instead of files.
-
-
- {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}}
- Array of {{domxref("FileSystemEntry")}} objects describing the currently-selected files or directories.
-
-
-
-
-
- Properties that apply only to text/number-containing or elements
-
-
- autocomplete
- string
: Returns / Sets the element's {{htmlattrxref("autocomplete", "input")}} attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden
, checkbox
, radio
, file
, or a button type (button
, submit
, reset
, image
). Possible values are:
- "on": the browser can autocomplete the value using previously stored value
- "off": the user must explicity enter a value
-
-
- maxLength
- long
: Returns / Sets the element's {{ htmlattrxref("maxlength", "input") }} attribute, containing the maximum l ength of characters (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.)
-
-
- size
- unsigned long
: Returns / Sets the element's {{ htmlattrxref("size", "input") }} attribute, containing size of the control . This value is in pixels unless the value of {{htmlattrxref("type","input")}} is text
or password
, in which case, it is an integer number of characters. Applies only when {{htmlattrxref("type","input")}} is set to text
, search
, tel
, url
, email
, or password
; otherwise it is ignored.
-
-
- pattern
- string
: Returns / Sets the element's {{ htmlattrxref("pattern", "input") }} attribute, containing a regular expression that the control's value is checked against. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text
, search
, tel
, url
or email
; otherwise it is ignored.
-
-
- placeholder
- string
: Returns / Sets the element's {{ htmlattrxref("placeholder", "input") }} attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text
, search
, tel
, url
or email
; otherwise it is ignored.
-
-
- readOnly
- boolean
: Returns / Sets the element's {{ htmlattrxref("readonly", "input") }} attribute, indicating that the user cannot modify the value of the control.
- This is ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden
, range
, color
, checkbox
, radio
, file
, or a button type.
-
-
- min
- string
: Returns / Sets the element's {{ htmlattrxref("min", "input") }} attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value.
-
-
- max
- string
: Returns / Sets the element's {{ htmlattrxref("max", "input") }} attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
-
-
- selectionStart
- unsigned long
: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element.
-
-
- selectionEnd
- unsigned long
: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
-
-
- selectionDirection
- string
: Returns / Sets the direction in which selection occurred. Possible values are:
- "forward"
if selection was performed in the start-to-end direction of the current locale,
- "backward"
for the opposite direction,
- "none"
if the direction is unknown."
-
-
-
-
-
- Properties not yet categorized
-
-
- defaultValue
- string:
Returns / Sets the default value as originally specified in the HTML that created this object.
-
-
- dirName
- string:
Returns / Sets the directionality of the element.
-
-
- accessKey
- string
: Returns a string containing a single character that switches input focus to the control when pressed.
-
-
- list
{{readonlyInline}}
- {{domxref("HTMLElement")}} object:
Returns the element pointed by the {{ htmlattrxref("list", "input") }} attribute. The property may be null
if no HTML element found in the same tree.
-
-
- multiple
- boolean
: Returns / Sets the element's {{ htmlattrxref("multiple", "input") }} attribute, indicating whether more than one value is possible (e.g., multiple files).
-
-
- files
{{readonlyInline}}
- {{domxref("FileList")}} array:
Returns the list of selected files.
-
-
- labels
{{readonlyInline}}
- {{domxref("NodeList")}} array:
Returns a list of {{ HTMLElement("label") }} elements that are labels for this element.
-
-
- step
- string:
Returns / Sets the element's {{ htmlattrxref("step", "input") }} attribute, which works with {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} to limit the increments at which a numeric or date-time value can be set. It can be the string any
or a positive floating point number. If this is not set to any
, the control accepts only values at multiples of the step value greater than the minimum.
-
-
- valueAsDate
- {{jsxref("Date")}} object:
Returns / Sets the value of the element, interpreted as a date, or null
if conversion is not possible.
-
-
- valueAsNumber
- double
: Returns the value of the element, interpreted as one of the following, in order:
-
- a time value
- a number
- NaN if conversion is impossible
-
-
-
-
- autocapitalize
{{experimental_inline}}
- string:
defines the capitalization behavior for user input. Valid values are none
, off
, characters
, words
, or sentences
.
-
-
-
-
-
- {{domxref("HTMLInputElement.align")}} {{Deprecated_Inline}}
- string:
represents the alignment of the element. Use CSS instead.
- {{domxref("HTMLInputElement.useMap")}} {{Deprecated_Inline}}
- string:
represents a client-side image map.
-
-
-方法
-
-
-
-
- focus()
- Focus on the input element; keystrokes will subsequently go to this element.
-
-
- blur()
- Removes focus from input; keystrokes will subsequently go nowhere.
-
-
- select()
- Selects the input text in the element, and focuses it so the user can subsequently replace the whole entry.
-
-
- click()
- Simulates a click on the element.
-
-
- setSelectionRange()
- Selects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property.
-
-
- setRangeText()
- Selects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property.
-
-
- setCustomValidity()
- Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
-
-
- checkValidity()
- Returns a {{jsxref("Boolean")}} that is false
if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{event("invalid")}} event at the element. It returns true
if the element is not a candidate for constraint validation, or if it satisfies its constraints.
-
-
-
-
-
- {{domxref("HTMLInputElement.stepDown()")}}
- Decrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception:
-
- if the method is not applicable to for the current {{htmlattrxref("type","input")}} value,
- if the element has no {{htmlattrxref("step","input")}} value,
- if the {{htmlattrxref("value","input")}} cannot be converted to a number,
- if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
-
-
- {{domxref("HTMLInputElement.stepUp()")}}
- Increments the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception:
-
- if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.,
- if the element has no {{htmlattrxref("step","input")}} value,
- if the {{htmlattrxref("value","input")}} cannot be converted to a number,
- if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
-
-
-
-
- {{domxref("HTMLInputElement.mozSetFileArray()")}}{{non-standard_inline}}
- Sets the files selected on the input to the given array of {{domxref("File")}} objects. This is an alternative to mozSetFileNameArray()
which can be used in frame scripts: a chrome script can open files as File objects and send them via message manager .
- {{domxref("HTMLInputElement.mozGetFileNameArray()")}}
- Returns an array of all the file names from the input.
- {{domxref("HTMLInputElement.mozSetFileNameArray()")}}
- Sets the filenames for the files selected on the input. Not for use in frame scripts , because it accesses the file system.
-
-
-規範
+- {{domxref("HTMLInputElement.align")}} {{Deprecated_Inline}}
+ - : `string:` represents the alignment of the element. _Use CSS instead._
+- {{domxref("HTMLInputElement.useMap")}} {{Deprecated_Inline}}
+ - : `string:` represents a client-side image map.
+
+## 方法
+
+| `focus()` | Focus on the input element; keystrokes will subsequently go to this element. |
+| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `blur()` | Removes focus from input; keystrokes will subsequently go nowhere. |
+| [`select()`](/en-US/docs/Web/API/HTMLInputElement/select) | Selects the input text in the element, and focuses it so the user can subsequently replace the whole entry. |
+| [`click()`](/en-US/docs/Web/API/HTMLInputElement/click) | Simulates a click on the element. |
+| [`setSelectionRange()`](/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) | Selects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property. |
+| `setRangeText()` | Selects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property. |
+| `setCustomValidity()` | Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. |
+| `checkValidity()` | Returns a {{jsxref("Boolean")}} that is `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{event("invalid")}} event at the element. It returns `true` if the element is not a candidate for constraint validation, or if it satisfies its constraints. |
+
+- {{domxref("HTMLInputElement.stepDown()")}}
+ - : Decrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: if the method is not applicable to for the current {{htmlattrxref("type","input")}} value,
+ - if the element has no {{htmlattrxref("step","input")}} value,
+ - if the {{htmlattrxref("value","input")}} cannot be converted to a number,
+ - if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
+- {{domxref("HTMLInputElement.stepUp()")}}
+ - : Increments the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.,
+ - if the element has no {{htmlattrxref("step","input")}} value,
+ - if the {{htmlattrxref("value","input")}} cannot be converted to a number,
+ - if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
+- {{domxref("HTMLInputElement.mozSetFileArray()")}}{{non-standard_inline}}
+ - : Sets the files selected on the input to the given array of {{domxref("File")}} objects. This is an alternative to `mozSetFileNameArray()` which can be used in frame scripts: a chrome script can [open files as File objects](/zh-TW/docs/Extensions/Using_the_DOM_File_API_in_chrome_code) and send them via [message manager](/en-US/Firefox/Multiprocess_Firefox/The_message_manager).
+- {{domxref("HTMLInputElement.mozGetFileNameArray()")}}
+ - : Returns an array of all the file names from the input.
+- {{domxref("HTMLInputElement.mozSetFileNameArray()")}}
+ - : Sets the filenames for the files selected on the input. Not for use in [frame scripts](/en-US/Firefox/Multiprocess_Firefox/Limitations_of_frame_scripts), because it accesses the file system.
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.HTMLInputElement")}}
-參見
+## 參見
-
- HTML element implementing this interface: {{ HTMLElement("input") }}.
-
+- HTML element implementing this interface: {{ HTMLElement("input") }}.
diff --git a/files/zh-tw/web/api/htmlmediaelement/index.md b/files/zh-tw/web/api/htmlmediaelement/index.md
index 22d47e8503731a..2068ebd6a90b7e 100644
--- a/files/zh-tw/web/api/htmlmediaelement/index.md
+++ b/files/zh-tw/web/api/htmlmediaelement/index.md
@@ -3,213 +3,177 @@ title: HTMLMediaElement
slug: Web/API/HTMLMediaElement
translation_of: Web/API/HTMLMediaElement
---
-{{APIRef("HTML DOM")}}
-
-The HTMLMediaElement
interface adds to {{domxref("HTMLElement")}} the properties and methods needed to support basic media-related capabilities that are common to audio and video. The {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} elements both inherit this interface.
-
-{{InheritanceDiagram(600, 120)}}
-
-屬性
-
-這個介面從{{domxref("HTMLElement")}}、{{domxref("Element")}}、{{domxref("Node")}},和{{domxref("EventTarget")}}繼承了屬性
-
-
- {{domxref("HTMLMediaElement.audioTracks")}}
- {{domxref("AudioTrackList")}} 會列出包含在該媒體元素內部的{{domxref("AudioTrack")}}物件。
- {{domxref("HTMLMediaElement.autoplay")}}
- 是一個布林值,表達了HTML中是否有{{htmlattrxref("autoplay", "video")}}屬性;意即;表明是否只要在媒體可以播放且不中斷的時候,能夠自動播放。
- 在網站上自動播放音訊(或是有音訊的影片),可能是惱人的使用者體驗;因此,應該盡可能地避免。如果你必須要有自動播放的功能,你應該讓它是可選擇的(讓使用者特地去啟動)。 However, this can be useful when creating media elements whose source will be set at a later time, under user control.
-
- {{domxref("HTMLMediaElement.buffered")}} {{readonlyinline}}
- 回傳一個{{domxref("TimeRanges")}}物件,表示媒體當下buffered
屬性被瀏覽器存取時的緩存(如果有的話)區間。
- {{domxref("HTMLMediaElement.controller")}}
- Is a {{domxref("MediaController")}} object that represents the media controller assigned to the element, or null
if none is assigned.
- {{domxref("HTMLMediaElement.controls")}}
- Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("controls", "video")}} HTML attribute, indicating whether user interface items for controlling the resource should be displayed.
- {{domxref("HTMLMediaElement.controlsList")}} {{readonlyinline}}
- Returns a {{domxref("DOMTokenList")}} that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The DOMTokenList
takes one or more of three possible values: nodownload
, nofullscreen
, and noremoteplayback
.
- {{domxref("HTMLMediaElement.crossOrigin")}}
- Is a {{domxref("DOMString")}} indicating the CORS setting for this media element.
- {{domxref("HTMLMediaElement.currentSrc")}} {{readonlyinline}}
- Returns a {{domxref("DOMString")}} with the absolute URL of the chosen media resource.
- {{domxref("HTMLMediaElement.currentTime")}}
- Is a double
indicating the current playback time in seconds. Setting this value seeks the media to the new time.
- {{domxref("HTMLMediaElement.defaultMuted")}}
- Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("muted", "video")}} HTML attribute, which indicates whether the media element's audio output should be muted by default.
- {{domxref("HTMLMediaElement.defaultPlaybackRate")}}
- Is a double
indicating the default playback rate for the media.
- {{domxref("HTMLMediaElement.disableRemotePlayback")}}
- Is a {{jsxref('Boolean')}} that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.
- {{domxref("HTMLMediaElement.duration")}} {{readonlyinline}}
- Returns a double
indicating the length of the media in seconds, or 0 if no media data is available.
- {{domxref("HTMLMediaElement.ended")}} {{readonlyinline}}
- Returns a {{jsxref('Boolean')}} that indicates whether the media element has finished playing.
- {{domxref("HTMLMediaElement.error")}} {{readonlyinline}}
- Returns a {{domxref("MediaError")}} object for the most recent error, or null
if there has not been an error.
- {{domxref("HTMLMediaElement.loop")}}
- Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("loop", "video")}} HTML attribute, which indicates whether the media element should start over when it reaches the end.
- {{domxref("HTMLMediaElement.mediaGroup")}}
- Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("mediagroup", "video")}} HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common {{domxref('MediaController')}}.
- {{domxref("HTMLMediaElement.mediaKeys")}} {{readonlyinline}} {{experimental_inline}}
- Returns a {{domxref("MediaKeys")}} object or null
. MediaKeys is a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback.
- {{domxref("HTMLMediaElement.mozAudioCaptured")}} {{readonlyinline}} {{non-standard_inline}}
- Returns a {{jsxref('Boolean')}}. Related to audio stream capture.
- {{domxref("HTMLMediaElement.mozFragmentEnd")}} {{non-standard_inline}}
- Is a double
that provides access to the fragment end time if the media element has a fragment URI for currentSrc
, otherwise it is equal to the media duration.
- {{domxref("HTMLMediaElement.mozFrameBufferLength")}} {{non-standard_inline}} {{deprecated_inline}}
-
- Is a unsigned long
that indicates the number of samples that will be returned in the framebuffer of each MozAudioAvailable
event. This number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total).
-
- The mozFrameBufferLength
property can be set to a new value for lower latency, larger amounts of data, etc. The size given must be a number between 512 and 16384. Using any other size results in an exception being thrown. The best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or MozAudioAvailable
events have begun firing.
-
- {{domxref("HTMLMediaElement.mozSampleRate")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
- Returns a double
representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio.
- {{domxref("HTMLMediaElement.muted")}}
- Is a {{jsxref('Boolean')}} that determines whether audio is muted. true
if the audio is muted and false
otherwise.
- {{domxref("HTMLMediaElement.networkState")}} {{readonlyinline}}
- Returns a unsigned short
(enumeration) indicating the current state of fetching the media over the network.
- {{domxref("HTMLMediaElement.paused")}} {{readonlyinline}}
- Returns a {{jsxref('Boolean')}} that indicates whether the media element is paused.
- {{domxref("HTMLMediaElement.playbackRate")}}
- Is a double
that indicates the rate at which the media is being played back.
- {{domxref("HTMLMediaElement.played")}} {{readonlyinline}}
- Returns a {{domxref('TimeRanges')}} object that contains the ranges of the media source that the browser has played, if any.
- {{domxref("HTMLMediaElement.preload")}}
- Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("preload", "video")}} HTML attribute, indicating what data should be preloaded, if any. Possible values are: none
, metadata
, auto
.
- {{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}}
- Is a {{jsxref('Boolean')}} that determines if the pitch of the sound will be preserved. If set to false
, the pitch will adjust to the speed of the audio. This is implemented with prefixes in Firefox (mozPreservesPitch
) and WebKit (webkitPreservesPitch
).
- {{domxref("HTMLMediaElement.readyState")}} {{readonlyinline}}
- Returns a unsigned short
(enumeration) indicating the readiness state of the media.
- {{domxref("HTMLMediaElement.seekable")}} {{readonlyinline}}
- Returns a {{domxref('TimeRanges')}} object that contains the time ranges that the user is able to seek to, if any.
- {{domxref("HTMLMediaElement.seeking")}} {{readonlyinline}}
- Returns a {{jsxref('Boolean')}} that indicates whether the media is in the process of seeking to a new position.
- {{domxref("HTMLMediaElement.sinkId")}} {{readonlyinline}} {{experimental_inline}}
- Returns a {{domxref("DOMString")}} that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the MediaDeviceInfo.deviceid
values returned from {{domxref("MediaDevices.enumerateDevices()")}}, id-multimedia
, or id-communications
.
- {{domxref("HTMLMediaElement.src")}}
- Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("src", "video")}} HTML attribute, which contains the URL of a media resource to use.
- {{domxref("HTMLMediaElement.srcObject")}}
- Is a {{domxref('MediaStream')}} representing the media to play or that has played in the current HTMLMediaElement
, or null
if not assigned.
- {{domxref("HTMLMediaElement.textTracks")}} {{readonlyinline}}
- Returns the list of {{domxref("TextTrack")}} objects contained in the element.
- {{domxref("HTMLMediaElement.videoTracks")}} {{readonlyinline}}
- Returns the list of {{domxref("VideoTrack")}} objects contained in the element.
-
-
Gecko supports only single track playback, and the parsing of tracks' metadata is only available for media with the Ogg container format.
-
-
- {{domxref("HTMLMediaElement.volume")}}
- Is a double
indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
-
-
-Event handlers
-
-
-
- {{domxref("HTMLMediaElement.onencrypted")}}
- Sets the {{domxref('EventHandler')}} called when the media is encrypted.
- {{domxref("HTMLMediaElement.onwaitingforkey")}}
- Sets the {{domxref('EventHandler')}} called when playback is blocked while waiting for an encryption key.
-
-
-Obsolete attributes
-
-These attributes are obsolete and should not be used, even if a browser still supports them.
-
-
-
-
- {{domxref("HTMLMediaElement.initialTime")}} {{readonlyinline}} {{non-standard_inline}} {{Deprecated_Inline}}
- Returns a double
that indicates the initial playback position in seconds.
- {{domxref("HTMLMediaElement.mozChannels")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
- Returns a double
representing the number of channels in the audio resource (e.g., 2
for stereo).
-
-
-Obsolete event handlers
-
-
-
-
- {{domxref("HTMLMediaElement.onmozinterruptbegin")}} {{non-standard_inline}} {{Deprecated_Inline}}
- Sets the {{event("Event_handlers", "event handler")}} called when the media element is interrupted because of the Audio Channel manager. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
- {{domxref("HTMLMediaElement.onmozinterruptend")}} {{non-standard_inline}} {{Deprecated_Inline}}
- Sets the {{domxref('EventHandler')}} called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
-
-
-
-
-
-
-Methods
-
-This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref('Element')}}, {{domxref('Node')}}, and {{domxref('EventTarget')}}.
-
-
- {{domxref("HTMLMediaElement.addTextTrack()")}}
- Adds a text track (such as a track for subtitles) to a media element.
- {{domxref("HTMLMediaElement.captureStream()")}} {{experimental_inline}}
- Returns {{domxref("MediaStream")}}, captures a stream of the media content.
- {{domxref("HTMLMediaElement.canPlayType()")}}
- Determines whether the specified media type can be played back.
- {{domxref("HTMLMediaElement.fastSeek()")}}
- Directly seeks to the given time.
- {{domxref("HTMLMediaElement.load()")}}
- Resets the media element and restarts the media resource. Any pending events are discarded. How much media data is fetched is still affected by the preload
attribute. This method can be useful for releasing resources after any src
attribute and source
element descendants have been removed. Otherwise, it is usually unnecessary to use this method, unless required to rescan source
element children after dynamic changes.
- {{domxref("HTMLMediaElement.mozCaptureStream()")}} {{non-standard_inline}}
- [enter description]
- {{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{non-standard_inline}}
- [enter description]
- {{domxref("HTMLMediaElement.mozGetMetadata()")}} {{non-standard_inline}}
- Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as {key: value}
pairs. A separate copy of the data is returned each time the method is called. This method must be called after the loadedmetadata event fires.
- {{domxref("HTMLMediaElement.pause()")}}
- Pauses the media playback.
- {{domxref("HTMLMediaElement.play()")}}
- Begins playback of the media.
- {{domxref("HTMLMediaElement.seekToNextFrame()")}} {{non-standard_inline}} {{experimental_inline}}
- Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.
- {{domxref("HTMLMediaElement.setMediaKeys()")}} {{experimental_inline}}
- Returns {{jsxref("Promise")}}. Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback.
- {{domxref("HTMLMediaElement.setSinkId()")}} {{experimental_inline}}
- Sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is authorized to use the specified device.
-
-
-Obsolete methods
-
-These methods are obsolete and should not be used, even if a browser still supports them.
-
-
-
-
- {{domxref("HTMLMediaElement.mozLoadFrom()")}} {{non-standard_inline}} {{deprecated_inline}}
- This method, available only in Mozilla's implementation, loads data from another media element. This works similarly to load()
except that instead of running the normal resource selection algorithm, the source is simply set to the other
element's currentSrc
. This is optimized so this element gets access to all of the other
element's cached and buffered data; in fact, the two elements share downloaded data, so data downloaded by either element is available to both.
-
-
-
-
-Specifications
+{{APIRef("HTML DOM")}}
+
+The **`HTMLMediaElement`** interface adds to {{domxref("HTMLElement")}} the properties and methods needed to support basic media-related capabilities that are common to audio and video. The {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} elements both inherit this interface.
+
+{{InheritanceDiagram(600, 120)}}
+
+## 屬性
+
+_這個介面從{{domxref("HTMLElement")}}、{{domxref("Element")}}、{{domxref("Node")}},和{{domxref("EventTarget")}}繼承了屬性_
+
+- {{domxref("HTMLMediaElement.audioTracks")}}
+ - : {{domxref("AudioTrackList")}} 會列出包含在該媒體元素內部的{{domxref("AudioTrack")}}物件。
+- {{domxref("HTMLMediaElement.autoplay")}}
+ - : 是一個布林值,表達了 HTML 中是否有{{htmlattrxref("autoplay", "video")}}屬性;意即;表明是否只要在媒體可以播放且不中斷的時候,能夠自動播放。
+
+ > **備註:** 在網站上自動播放音訊(或是有音訊的影片),可能是惱人的使用者體驗;因此,應該盡可能地避免。如果你必須要有自動播放的功能,你應該讓它是可選擇的(讓使用者特地去啟動)。 However, this can be useful when creating media elements whose source will be set at a later time, under user control.
+- {{domxref("HTMLMediaElement.buffered")}} {{readonlyinline}}
+ - : 回傳一個{{domxref("TimeRanges")}}物件,表示媒體當下`buffered`屬性被瀏覽器存取時的緩存(如果有的話)區間。
+- {{domxref("HTMLMediaElement.controller")}}
+ - : Is a {{domxref("MediaController")}} object that represents the media controller assigned to the element, or `null` if none is assigned.
+- {{domxref("HTMLMediaElement.controls")}}
+ - : Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("controls", "video")}} HTML attribute, indicating whether user interface items for controlling the resource should be displayed.
+- {{domxref("HTMLMediaElement.controlsList")}} {{readonlyinline}}
+ - : Returns a {{domxref("DOMTokenList")}} that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The `DOMTokenList` takes one or more of three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`.
+- {{domxref("HTMLMediaElement.crossOrigin")}}
+ - : Is a {{domxref("DOMString")}} indicating the [CORS setting](/zh-TW/docs/Web/HTML/CORS_settings_attributes) for this media element.
+- {{domxref("HTMLMediaElement.currentSrc")}} {{readonlyinline}}
+ - : Returns a {{domxref("DOMString")}} with the absolute URL of the chosen media resource.
+- {{domxref("HTMLMediaElement.currentTime")}}
+ - : Is a `double` indicating the current playback time in seconds. Setting this value seeks the media to the new time.
+- {{domxref("HTMLMediaElement.defaultMuted")}}
+ - : Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("muted", "video")}} HTML attribute, which indicates whether the media element's audio output should be muted by default.
+- {{domxref("HTMLMediaElement.defaultPlaybackRate")}}
+ - : Is a `double` indicating the default playback rate for the media.
+- {{domxref("HTMLMediaElement.disableRemotePlayback")}}
+ - : Is a {{jsxref('Boolean')}} that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.
+- {{domxref("HTMLMediaElement.duration")}} {{readonlyinline}}
+ - : Returns a `double` indicating the length of the media in seconds, or 0 if no media data is available.
+- {{domxref("HTMLMediaElement.ended")}} {{readonlyinline}}
+ - : Returns a {{jsxref('Boolean')}} that indicates whether the media element has finished playing.
+- {{domxref("HTMLMediaElement.error")}} {{readonlyinline}}
+ - : Returns a {{domxref("MediaError")}} object for the most recent error, or `null` if there has not been an error.
+- {{domxref("HTMLMediaElement.loop")}}
+ - : Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("loop", "video")}} HTML attribute, which indicates whether the media element should start over when it reaches the end.
+- {{domxref("HTMLMediaElement.mediaGroup")}}
+ - : Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("mediagroup", "video")}} HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common {{domxref('MediaController')}}.
+- {{domxref("HTMLMediaElement.mediaKeys")}} {{readonlyinline}} {{experimental_inline}}
+ - : Returns a {{domxref("MediaKeys")}} object or `null`. MediaKeys is a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback.
+- {{domxref("HTMLMediaElement.mozAudioCaptured")}} {{readonlyinline}} {{non-standard_inline}}
+ - : Returns a {{jsxref('Boolean')}}. Related to audio stream capture.
+- {{domxref("HTMLMediaElement.mozFragmentEnd")}} {{non-standard_inline}}
+ - : Is a `double` that provides access to the fragment end time if the media element has a fragment URI for `currentSrc`, otherwise it is equal to the media duration.
+- {{domxref("HTMLMediaElement.mozFrameBufferLength")}} {{non-standard_inline}} {{deprecated_inline}}
+ - : Is a `unsigned long` that indicates the number of samples that will be returned in the framebuffer of each `MozAudioAvailable` event. This number is a total for all channels, and by default is set to be the number of channels \* 1024 (e.g., 2 channels \* 1024 samples = 2048 total).The `mozFrameBufferLength` property can be set to a new value for lower latency, larger amounts of data, etc. The size given _must_ be a number between 512 and 16384. Using any other size results in an exception being thrown. The best time to set a new length is after the [loadedmetadata](/zh-TW/docs/Web/Events/loadedmetadata) event fires, when the audio info is known, but before the audio has started or `MozAudioAvailable` events have begun firing.
+- {{domxref("HTMLMediaElement.mozSampleRate")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+ - : Returns a `double` representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio.
+- {{domxref("HTMLMediaElement.muted")}}
+ - : Is a {{jsxref('Boolean')}} that determines whether audio is muted. `true` if the audio is muted and `false` otherwise.
+- {{domxref("HTMLMediaElement.networkState")}} {{readonlyinline}}
+ - : Returns a `unsigned short` (enumeration) indicating the current state of fetching the media over the network.
+- {{domxref("HTMLMediaElement.paused")}} {{readonlyinline}}
+ - : Returns a {{jsxref('Boolean')}} that indicates whether the media element is paused.
+- {{domxref("HTMLMediaElement.playbackRate")}}
+ - : Is a `double` that indicates the rate at which the media is being played back.
+- {{domxref("HTMLMediaElement.played")}} {{readonlyinline}}
+ - : Returns a {{domxref('TimeRanges')}} object that contains the ranges of the media source that the browser has played, if any.
+- {{domxref("HTMLMediaElement.preload")}}
+ - : Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("preload", "video")}} HTML attribute, indicating what data should be preloaded, if any. Possible values are: `none`, `metadata`, `auto`.
+- {{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}}
+ - : Is a {{jsxref('Boolean')}} that determines if the pitch of the sound will be preserved. If set to `false`, the pitch will adjust to the speed of the audio. This is implemented with prefixes in Firefox (`mozPreservesPitch`) and WebKit (`webkitPreservesPitch`).
+- {{domxref("HTMLMediaElement.readyState")}} {{readonlyinline}}
+ - : Returns a `unsigned short` (enumeration) indicating the readiness state of the media.
+- {{domxref("HTMLMediaElement.seekable")}} {{readonlyinline}}
+ - : Returns a {{domxref('TimeRanges')}} object that contains the time ranges that the user is able to seek to, if any.
+- {{domxref("HTMLMediaElement.seeking")}} {{readonlyinline}}
+ - : Returns a {{jsxref('Boolean')}} that indicates whether the media is in the process of seeking to a new position.
+- {{domxref("HTMLMediaElement.sinkId")}} {{readonlyinline}} {{experimental_inline}}
+ - : Returns a {{domxref("DOMString")}} that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the `MediaDeviceInfo.deviceid` values returned from {{domxref("MediaDevices.enumerateDevices()")}}, `id-multimedia`, or `id-communications`.
+- {{domxref("HTMLMediaElement.src")}}
+ - : Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("src", "video")}} HTML attribute, which contains the URL of a media resource to use.
+- {{domxref("HTMLMediaElement.srcObject")}}
+ - : Is a {{domxref('MediaStream')}} representing the media to play or that has played in the current `HTMLMediaElement`, or `null` if not assigned.
+- {{domxref("HTMLMediaElement.textTracks")}} {{readonlyinline}}
+ - : Returns the list of {{domxref("TextTrack")}} objects contained in the element.
+- {{domxref("HTMLMediaElement.videoTracks")}} {{readonlyinline}}
+ - : Returns the list of {{domxref("VideoTrack")}} objects contained in the element.
+
+ > **備註:** Gecko supports only single track playback, and the parsing of tracks' metadata is only available for media with the Ogg container format.
+- {{domxref("HTMLMediaElement.volume")}}
+ - : Is a `double` indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
+
+### Event handlers
+
+- {{domxref("HTMLMediaElement.onencrypted")}}
+
+ - : Sets the {{domxref('EventHandler')}} called when the media is encrypted.
+
+- {{domxref("HTMLMediaElement.onwaitingforkey")}}
+ - : Sets the {{domxref('EventHandler')}} called when playback is blocked while waiting for an encryption key.
+
+## Obsolete attributes
+
+These attributes are obsolete and should not be used, even if a browser still supports them.
+
+- {{domxref("HTMLMediaElement.initialTime")}} {{readonlyinline}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Returns a `double` that indicates the initial playback position in seconds.
+- {{domxref("HTMLMediaElement.mozChannels")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+ - : Returns a `double` representing the number of channels in the audio resource (e.g., `2` for stereo).
+
+### Obsolete event handlers
+
+- {{domxref("HTMLMediaElement.onmozinterruptbegin")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Sets the {{event("Event_handlers", "event handler")}} called when the media element is interrupted because of the Audio Channel manager. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
+- {{domxref("HTMLMediaElement.onmozinterruptend")}} {{non-standard_inline}} {{Deprecated_Inline}}
+ - : Sets the {{domxref('EventHandler')}} called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
+
+## Methods
+
+_This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref('Element')}}, {{domxref('Node')}}, and {{domxref('EventTarget')}}._
+
+- {{domxref("HTMLMediaElement.addTextTrack()")}}
+ - : Adds a text track (such as a track for subtitles) to a media element.
+- {{domxref("HTMLMediaElement.captureStream()")}} {{experimental_inline}}
+ - : Returns {{domxref("MediaStream")}}, captures a stream of the media content.
+- {{domxref("HTMLMediaElement.canPlayType()")}}
+ - : Determines whether the specified media type can be played back.
+- {{domxref("HTMLMediaElement.fastSeek()")}}
+ - : Directly seeks to the given time.
+- {{domxref("HTMLMediaElement.load()")}}
+ - : Resets the media element and restarts the media resource. Any pending events are discarded. How much media data is fetched is still affected by the `preload` attribute. This method can be useful for releasing resources after any `src` attribute and `source` element descendants have been removed. Otherwise, it is usually unnecessary to use this method, unless required to rescan `source` element children after dynamic changes.
+- {{domxref("HTMLMediaElement.mozCaptureStream()")}} {{non-standard_inline}}
+ - : \[enter description]
+- {{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{non-standard_inline}}
+ - : \[enter description]
+- {{domxref("HTMLMediaElement.mozGetMetadata()")}} {{non-standard_inline}}
+ - : Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as `{key: value}` pairs. A separate copy of the data is returned each time the method is called. This method must be called after the [loadedmetadata](/zh-TW/docs/Web/Events/loadedmetadata) event fires.
+- {{domxref("HTMLMediaElement.pause()")}}
+ - : Pauses the media playback.
+- {{domxref("HTMLMediaElement.play()")}}
+ - : Begins playback of the media.
+- {{domxref("HTMLMediaElement.seekToNextFrame()")}} {{non-standard_inline}} {{experimental_inline}}
+ - : Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.
+- {{domxref("HTMLMediaElement.setMediaKeys()")}} {{experimental_inline}}
+ - : Returns {{jsxref("Promise")}}. Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback.
+- {{domxref("HTMLMediaElement.setSinkId()")}} {{experimental_inline}}
+ - : Sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is authorized to use the specified device.
+
+## Obsolete methods
+
+These methods are obsolete and should not be used, even if a browser still supports them.
+
+- {{domxref("HTMLMediaElement.mozLoadFrom()")}} {{non-standard_inline}} {{deprecated_inline}}
+ - : This method, available only in Mozilla's implementation, loads data from another media element. This works similarly to `load()` except that instead of running the normal resource selection algorithm, the source is simply set to the `other` element's `currentSrc`. This is optimized so this element gets access to all of the `other` element's cached and buffered data; in fact, the two elements share downloaded data, so data downloaded by either element is available to both.
+
+## Specifications
{{Specifications}}
-Browser compatibility
+## Browser compatibility
+{{Compat("api.HTMLMediaElement")}}
+## See also
-{{Compat("api.HTMLMediaElement")}}
+- References
-See also
+ - {{HTMLElement("video")}} and {{HTMLElement("audio")}} HTML elements.
+ - {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} interfaces, derived from `HTMLMediaElement`.
-
- References
-
- {{HTMLElement("video")}} and {{HTMLElement("audio")}} HTML elements.
- {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} interfaces, derived from HTMLMediaElement
.
-
-
- Articles
-
-
-
+- Articles
+
+ - [Using HTML5 audio and video](/zh-TW/docs/Using_HTML5_audio_and_video)
+ - [Media formats supported by the audio and video elements](/zh-TW/docs/Media_formats_supported_by_the_audio_and_video_elements)
+ - [Web Audio API](/zh-TW/docs/Web_Audio_API)
diff --git a/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.md b/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.md
index 5efbab72b830d3..1a2f031330e81c 100644
--- a/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.md
+++ b/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.md
@@ -3,24 +3,24 @@ title: HTMLSelectElement.checkValidity()
slug: Web/API/HTMLSelectElement/checkValidity
translation_of: Web/API/HTMLSelectElement/checkValidity
---
-{{ APIRef("HTML DOM") }}
+{{ APIRef("HTML DOM") }}
-HTMLSelectElement.checkValidity()
方法會檢查元素是否有任何的檢核、驗證條件,並且檢查是否滿足這些條件。如果元素沒有通過這些檢核,瀏覽器會於該元素上觸發一個可取消的 {{event("invalid")}} 事件,並回傳 false
。
+**`HTMLSelectElement.checkValidity()`** 方法會檢查元素是否有任何的檢核、驗證條件,並且檢查是否滿足這些條件。如果元素沒有通過這些檢核,瀏覽器會於該元素上觸發一個可取消的 {{event("invalid")}} 事件,並回傳 `false`。
-語法
+## 語法
-var result = selectElt .checkValidity();
+```js
+var result = selectElt.checkValidity();
+```
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.HTMLSelectElement.checkValidity")}}
-參見
+## 參見
-
+- [Form validation.](/zh-TW/docs/Web/Guide/HTML/HTML5/Constraint_validation)
diff --git a/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.md b/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.md
index b182f5d7802bb3..1515fdf5a517b5 100644
--- a/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.md
+++ b/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.md
@@ -3,30 +3,28 @@ title: HTMLSelectElement.setCustomValidity()
slug: Web/API/HTMLSelectElement/setCustomValidity
translation_of: Web/API/HTMLSelectElement/setCustomValidity
---
-{{ APIRef("HTML DOM") }}
+{{ APIRef("HTML DOM") }}
-HTMLSelectElement.setCustomValidity()
方法可為指定的元素設定自定義檢核訊息。使用空字串表示元素沒有 發生違反自定檢核條件的錯誤。
+**`HTMLSelectElement.setCustomValidity()`** 方法可為指定的元素設定自定義檢核訊息。使用空字串表示元素*沒有*發生違反自定檢核條件的錯誤。
-語法
+## 語法
-selectElt .setCustomValidity(string );
+```js
+selectElt.setCustomValidity(string);
+```
-參數
+### 參數
-
- string 為 {{domxref("DOMString")}},代表錯誤訊息。
-
+- _string_ 為 {{domxref("DOMString")}},代表錯誤訊息。
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
-{{Compat("api.HTMLSelectElement.setCustomValidity")}}
+{{Compat("api.HTMLSelectElement.setCustomValidity")}}
-參見
+## 參見
-
+- [表單驗證](/zh-TW/docs/Web/Guide/HTML/HTML5/Constraint_validation)
diff --git a/files/zh-tw/web/api/idbdatabase/index.md b/files/zh-tw/web/api/idbdatabase/index.md
index 3fc2b19e314531..0599fb4f6265da 100644
--- a/files/zh-tw/web/api/idbdatabase/index.md
+++ b/files/zh-tw/web/api/idbdatabase/index.md
@@ -3,75 +3,62 @@ title: IDBDatabase
slug: Web/API/IDBDatabase
translation_of: Web/API/IDBDatabase
---
-{{APIRef("IndexedDB")}}
-
-
-
The IDBDatabase
interface of the IndexedDB API provides a connection to a database ; you can use an IDBDatabase
object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.
-
-
{{AvailableInWorkers}}
-
-
-
-
Note : Everything you do in IndexedDB always happens in the context of a transaction , representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.
-
-
-
-
Note : Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}.) Previously in a readwrite
transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the complete
event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The complete
event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete
event by creating a transaction using the experimental (non-standard) readwriteflush
mode (see {{domxref("IDBDatabase.transaction")}}.
-
-
-Methods
-
-Inherits from: EventTarget
-
-
- {{domxref("IDBDatabase.close()")}}
- Returns immediately and closes the connection to a database in a separate thread.
- {{domxref("IDBDatabase.createObjectStore()")}}
- Creates and returns a new object store or index.
- {{domxref("IDBDatabase.deleteObjectStore()")}}
- Destroys the object store with the given name in the connected database, along with any indexes that reference it.
- {{domxref("IDBDatabase.transaction()")}}
- Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.
-
-
-屬性
-
-
- {{domxref("IDBDatabase.name")}} {{readonlyInline}}
- A {{ domxref("DOMString") }} that contains the name of the connected database.
- {{domxref("IDBDatabase.version")}} {{readonlyInline}}
- A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string.
- {{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}
- A {{ domxref("DOMStringList") }} that contains a list of the names of the object stores currently in the connected database.
-
-
-Event handlers
-
-
- {{domxref("IDBDatabase.onabort")}}
- Fires when access of the database is aborted.
- {{domxref("IDBDatabase.onerror")}}
- Fires when access to the database fails.
- {{domxref("IDBDatabase.onversionchange")}}
-
- Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or
{{domxref("IDBFactory.deleteDatabase")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.
-
-
-
-範例
-
-In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our To-do Notifications app (view example live .)
-
-// Let us open our database
+{{APIRef("IndexedDB")}}
+
+The **`IDBDatabase`** interface of the IndexedDB API provides a [connection to a database](/zh-TW/docs/IndexedDB#database_connection); you can use an `IDBDatabase` object to open a [transaction](/zh-TW/docs/IndexedDB#gloss_transaction) on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.
+
+{{AvailableInWorkers}}
+
+> **備註:** Everything you do in IndexedDB always happens in the context of a [transaction](/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_transaction), representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.
+
+> **備註:** Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}.) Previously in a `readwrite` transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the `complete` event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The `complete` event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see {{domxref("IDBDatabase.transaction")}}.
+
+## Methods
+
+Inherits from: [EventTarget](/zh-TW/docs/DOM/EventTarget)
+
+- {{domxref("IDBDatabase.close()")}}
+ - : Returns immediately and closes the connection to a database in a separate thread.
+- {{domxref("IDBDatabase.createObjectStore()")}}
+ - : Creates and returns a new object store or index.
+- {{domxref("IDBDatabase.deleteObjectStore()")}}
+ - : Destroys the object store with the given name in the connected database, along with any indexes that reference it.
+- {{domxref("IDBDatabase.transaction()")}}
+ - : Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.
+
+## 屬性
+
+- {{domxref("IDBDatabase.name")}} {{readonlyInline}}
+ - : A {{ domxref("DOMString") }} that contains the name of the connected database.
+- {{domxref("IDBDatabase.version")}} {{readonlyInline}}
+ - : A [64-bit integer]() that contains the version of the connected database. When a database is first created, this attribute is an empty string.
+- {{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}
+ - : A {{ domxref("DOMStringList") }} that contains a list of the names of the [object stores](/zh-TW/docs/IndexedDB#gloss_object_store) currently in the connected database.
+
+### Event handlers
+
+- {{domxref("IDBDatabase.onabort")}}
+ - : Fires when access of the database is aborted.
+- {{domxref("IDBDatabase.onerror")}}
+ - : Fires when access to the database fails.
+- {{domxref("IDBDatabase.onversionchange")}}
+ - : Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or` `{{domxref("IDBFactory.deleteDatabase")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.
+
+## 範例
+
+In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our [To-do Notifications](https://github.com/mdn/to-do-notifications/) app ([view example live](http://mdn.github.io/to-do-notifications/).)
+
+```js
+// Let us open our database
var DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these two event handlers act on the IDBDatabase object, when the database is opened successfully, or not
DBOpenRequest.onerror = function(event) {
- note.innerHTML += '<li>Error loading database.</li>';
+ note.innerHTML += ' Error loading database. ';
};
DBOpenRequest.onsuccess = function(event) {
- note.innerHTML += '<li>Database initialised.</li>';
+ note.innerHTML += 'Database initialised. ';
// store the result of opening the database in the db variable. This is used a lot later on
db = DBOpenRequest.result;
@@ -88,7 +75,7 @@ translation_of: Web/API/IDBDatabase
var db = event.target.result;
db.onerror = function(event) {
- note.innerHTML += '<li>Error loading database.</li>';
+ note.innerHTML += 'Error loading database. ';
};
// Create an objectStore for this database using IDBDatabase.createObjectStore
@@ -105,31 +92,30 @@ translation_of: Web/API/IDBDatabase
objectStore.createIndex("notified", "notified", { unique: false });
- note.innerHTML += '<li>Object store created.</li>';
- };
+ note.innerHTML += 'Object store created. ';
+ };
+```
-This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.
+This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.
- var objectStore = db.transaction('toDoList').objectStore('toDoList');
+```js
+ var objectStore = db.transaction('toDoList').objectStore('toDoList');
+```
-規範
+## 規範
{{Specifications}}
-Browser compatibility
+## Browser compatibility
{{Compat("api.IDBDatabase")}}
-閱讀更多
-
-
- Using IndexedDB
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: To-do Notifications (view example live .)
-
+## 閱讀更多
-
+- [Using IndexedDB](/zh-TW/docs/Web/API/IndexedDB_API/Using_IndexedDB)
+- Starting transactions: {{domxref("IDBDatabase")}}
+- Using transactions: {{domxref("IDBTransaction")}}
+- Setting a range of keys: {{domxref("IDBKeyRange")}}
+- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
+- Using cursors: {{domxref("IDBCursor")}}
+- Reference example: [To-do Notifications](https://github.com/mdn/to-do-notifications/tree/gh-pages) ([view example live](http://mdn.github.io/to-do-notifications/).)
diff --git a/files/zh-tw/web/api/indexeddb_api/index.md b/files/zh-tw/web/api/indexeddb_api/index.md
index c2d4f2c93ab0f8..874286432231fa 100644
--- a/files/zh-tw/web/api/indexeddb_api/index.md
+++ b/files/zh-tw/web/api/indexeddb_api/index.md
@@ -7,77 +7,62 @@ tags:
- bug-840092
translation_of: Web/API/IndexedDB_API
---
-{{SeeCompatTable}}
+{{SeeCompatTable}}
-IndexedDB 為用戶端的儲存用 API,可用於大量的結構化資料,並透過索引功能而高效率搜尋資料。DOM Storage 適合儲存較少量的資料;IndexedDB 則適合大量結構化資料的儲存方案。
+IndexedDB 為用戶端的儲存用 API,可用於大量的結構化資料,並透過索引功能而高效率搜尋資料。[DOM Storage](/zh-TW/docs/DOM/Storage) 適合儲存較少量的資料;IndexedDB 則適合大量結構化資料的儲存方案。
-本篇文章僅為 API 物件的入門技術說明。若需進一步了解,則請參閱 IndexedDB 基本概念 。更多細節則可參閱使用 IndexedDB 。
+本篇文章僅為 API 物件的入門技術說明。若需進一步了解,則請參閱 [IndexedDB 基本概念](/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB)。更多細節則可參閱[使用 IndexedDB](/zh-TW/docs/IndexedDB/Using_IndexedDB)。
-IndexedDB 提供不同 APIs 用於同步與非同步的存取作業。同步 API 僅能用於Web Workers 之中,但尚未有瀏覽器支援同步API。非同步 API 則用於 Web Workers 內外均可,但 Firefox 目前尚未建構。
+IndexedDB 提供不同 APIs 用於同步與非同步的存取作業。同步 API 僅能用於[Web Workers](/zh-TW/docs/DOM/Worker) 之中,但尚未有瀏覽器支援同步 API。非同步 API 則用於 Web Workers 內外均可,但 Firefox 目前尚未建構。
-非同步 API
+## 非同步 API
-非同步API不會阻塞呼叫它的執行緒。若要非同步存取資料庫,可於 window 物件的 indexedDB 屬性上呼叫 open ()。此函式將回傳 IDBRequest 物件 (IDBOpenDBRequest),開始非同步存取資料庫;呼叫端程式利用IDBRequest物件上的事件來進行非同步溝通。
+非同步 API 不會阻塞呼叫它的執行緒。若要非同步存取資料庫,可於 [window](/zh-TW/docs/DOM/window) 物件的 [indexedDB](/zh-TW/docs/IndexedDB/IDBEnvironment#attr_indexedDB) 屬性上呼叫 [open](/zh-TW/docs/IndexedDB/IDBFactory#open)()。此函式將回傳 IDBRequest 物件 (IDBOpenDBRequest),開始非同步存取資料庫;呼叫端程式利用 IDBRequest 物件上的事件來進行非同步溝通。
-
-
注意: 在舊版瀏覽器 (Gecko 16 版之前的 indexedDB 屬性;Chrome 中的 webkitIndexedDB;IE 10 中的 msIndexedDB) 中的 indexedDB 物件,均具備前綴屬性。
-
+> **備註:** 在舊版瀏覽器 (Gecko 16 版之前的 indexedDB 屬性;Chrome 中的 webkitIndexedDB;IE 10 中的 msIndexedDB) 中的 indexedDB 物件,均具備前綴屬性。
-
+- [`IDBFactory`](/zh-TW/docs/IndexedDB/IDBFactory) 可存取資料庫。此介面是透過全域物件 `indexedDB` 所建構,因此成為 API 的切入點。
+- [`IDBCursor`](/zh-TW/docs/IndexedDB/IDBCursor) 將依序存取物件與索引。
+- [`IDBCursorWithValue`](/zh-TW/docs/IndexedDB/IDBCursorWithValue) 將依序存取物件與索引,並回傳指標 (Cursor) 的目前數值。
+- [`IDBDatabase`](/zh-TW/docs/IndexedDB/IDBDatabase) 代表到資料庫的連線。這也是能與資料庫互動的唯一方式。
+- [`IDBEnvironment`](/zh-TW/docs/IndexedDB/IDBEnvironment) 可存取用戶端的資料庫。此介面是透過 [window](/zh-TW/docs/DOM/window) 物件所建構。
+- [`IDBIndex`](/zh-TW/docs/IndexedDB/IDBIndex) 可存取索引的 Metadata。
+- [`IDBKeyRange`](/zh-TW/docs/IndexedDB/IDBKeyRange) 定義資料鍵範疇。
+- [`IDBObjectStore`](/zh-TW/docs/IndexedDB/IDBObjectStore) 代表物件存檔。
+- [`IDBOpenDBRequest`](/zh-TW/docs/IndexedDB/IDBOpenDBRequest) 代表「開啟資料庫」的請求。
+- [`IDBRequest`](/zh-TW/docs/IndexedDB/IDBRequest) 代表向非同步資料庫和資料庫物件發出之請求,也就是呼叫非同步方法後回傳值。
+- [`IDBTransaction`](/zh-TW/docs/IndexedDB/IDBTransaction) 代表一個交易。我們可以和資料庫進行交易,例如要求存取某一個物件存檔,以及決定要執行讀或寫的存取作業。
+- [`IDBVersionChangeEvent`](/zh-TW/docs/IndexedDB/IDBVersionChangeEvent) `則代表資料庫所變更的版本。`
-以下API在早期規範中有定義,但現已移除。這邊列出僅供參考:
+以下 API 在早期規範中有定義,但現已移除。這邊列出僅供參考:
-
+- [IDBVersionChangeRequest](/zh-TW/docs/IndexedDB/IDBVersionChangeRequest) 代表「更改資料庫版本」的請求。更改資料庫版本的方法已有不同 (呼叫 [IDBFactory.open()](/zh-TW/docs/IndexedDB/IDBFactory#open) 而不需同時呼叫 [IDBDatabase.setVersion()](/zh-TW/docs/IndexedDB/IDBDatabase#setVersion%28%29));而且[IDBOpenDBRequest](/zh-TW/docs/IndexedDB/IDBOpenDBRequest)已經整合了從 IDBVersionChangeRequest 中所移除之功能。
+- [IDBDatabaseException ](/zh-TW/docs/IndexedDB/IDBDatabaseException){{Deprecated_Inline}} 在執行資料庫作業時,代表可能遭遇的例外狀況。
-除了非同步API,也有應用在WebWorkers 內的同步API,但請注意目前還沒有瀏覽器支援同步API。這裡也提供 API 的同步版本 。
+除了非同步 API,也有應用在[WebWorkers](/zh-TW/docs/DOM/Using_web_workers)內的同步 API,但請注意目前還沒有瀏覽器支援同步 API。這裡也提供 [API 的同步版本](/zh-TW/docs/IndexedDB/Syncronous_API)。
-儲存限制
+## 儲存限制
-單一資料庫項目的容量/大小並沒有任何限制,但是各個 IndexedDB資料庫的容量就有限制。此限制,還有使用者介面的斷言 (Assert) 方式,又將因瀏覽器而有所不同:
+單一資料庫項目的容量/大小並沒有任何限制,但是各個 IndexedDB 資料庫的容量就有限制。此限制,還有使用者介面的斷言 (Assert) 方式,又將因瀏覽器而有所不同:
-
+- Firefox:對 IndexedDB 資料庫的容量並無限制。但若要儲存的 Blobs 超過 50 MB,使用者介面將會要求權限。若要修改此容量,則可透過 dom.indexedDB.warningQuota (可至 中設定) 設定自己所需的限制。
+- Google Chrome:請參閱 [https://developers.google.com/chrome...rage#temporary](https://developers.google.com/chrome/whitepapers/storage#temporary)
-範例
+## 範例
-Web 上的 IndexedDB 使用範例,是由 Marco Castelluccio 所提供。Marco 是 IndexedDB Mozilla DevDerby 的優勝者,而該得獎 Demo 為 eLibri ,屬於函式庫與 eBook 閱讀器的 App。
+Web 上的 IndexedDB 使用範例,是由 Marco Castelluccio 所提供。Marco 是 IndexedDB Mozilla DevDerby 的優勝者,而該得獎 Demo 為 [eLibri](/zh-TW/demos/detail/elibri),屬於函式庫與 eBook 閱讀器的 App。
+## 另可參閱
+- [IndexedDB 基本概念](/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB)
+- [使用 IndexedDB](/zh-TW/docs/IndexedDB/Using_IndexedDB)
+- [在 IndexedDB 中儲存影像與檔案](http://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/)
+- [使用 HTML5 IndexedDB 的簡易 TODO 清單](http://www.html5rocks.com/tutorials/indexeddb/todo/)
-另可參閱
+ > **備註:** 此線上教學是根據較舊版本的規格所列,因此無法搭配最新版的瀏覽器。新版本已移除其中的 `setVersion()` 函式。
-
+- [Indexed Database API 規格](http://www.w3.org/TR/IndexedDB/)
+- [IndexedDB — 儲存於自己的瀏覽器中](http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx)
+- [IndexedDB 範例](http://nparashuram.com/IndexedDB/trialtool/index.html)
+- 僅支援 WebSQL 的瀏覽器 (例如行動 WebKit),可適用 [IndexedDB Polyfill](https://github.com/axemclion/IndexedDBShim)
+- [JQuery IndexedDB 外掛程式](http://nparashuram.com/IndexedDBShim/)
diff --git a/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.md b/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.md
index 9ace36c0ee4149..2c63823be4670a 100644
--- a/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.md
+++ b/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.md
@@ -3,62 +3,88 @@ title: 使用IndexedDB
slug: Web/API/IndexedDB_API/Using_IndexedDB
translation_of: Web/API/IndexedDB_API/Using_IndexedDB
---
-IndexedDB提供了在瀏覽器上儲存保留資料的功能,藉由它,不論是線上或線下我們的應用都可以進行資料存取。
-關於本文
-本文會帶領各位操作非同步IndexedDB的API,如果不知道甚麼是IndexedDB,請先看看"IndexedDB基本礎念" 。
-基本操作步驟
-操作IndexedDB的基本步驟建議如下:
-
- 開啟資料庫和交易(transaction)。
- 建立物件存檔(object store)
- 發出資料庫操作請求,例如新增或取得資料。
-
-
- 聆聽對應DOM事件等待操作完成。
-
-
-
- 從result物件上取得結果進行其他工作。
-
-
-好了,知道了上述概念後,我們可以來實際做些甚麼。
-建立和結構資料庫
-由於IndexedDB的標準仍在演進,所以目前一些實作還需要加上瀏覽器前綴標示(如Gecko基礎瀏覽器的前綴標示為moz,WebKit基礎瀏覽器的前綴標示為webkit),瀏覽器的實作也可能會有所差異,不過一旦共識標準達成,無瀏覽器前綴標示實作將出現。其實,Internet Explorer 10, Firefox 16, Chrome 24已經有了無瀏覽器前綴標示實作。
-操作實驗性質的IndexedDB
-如果需要試驗瀏覽器的前綴標示,可以如下:
-// In the following line, you should include the prefixes of implementations you want to test.
+IndexedDB 提供了在瀏覽器上儲存保留資料的功能,藉由它,不論是線上或線下我們的應用都可以進行資料存取。
+
+## 關於本文
+
+本文會帶領各位操作非同步 IndexedDB 的 API,如果不知道甚麼是 IndexedDB,請先看看["IndexedDB 基本礎念"](/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB)。
+
+## 基本操作步驟
+
+操作 IndexedDB 的基本步驟建議如下:
+
+1. 開啟資料庫和交易(transaction)。
+2. 建立物件存檔(object store)
+3. 發出資料庫操作請求,例如新增或取得資料。
+4. 聆聽對應 DOM 事件等待操作完成。
+5. 從 result 物件上取得結果進行其他工作。
+
+好了,知道了上述概念後,我們可以來實際做些甚麼。
+
+## 建立和結構資料庫
+
+由於 IndexedDB 的標準仍在演進,所以目前一些實作還需要加上瀏覽器前綴標示(如 Gecko 基礎瀏覽器的前綴標示為 moz,WebKit 基礎瀏覽器的前綴標示為 webkit),瀏覽器的實作也可能會有所差異,不過一旦共識標準達成,無瀏覽器前綴標示實作將出現。其實,Internet Explorer 10, Firefox 16, Chrome 24 已經有了無瀏覽器前綴標示實作。
+
+### 操作實驗性質的 IndexedDB
+
+如果需要試驗瀏覽器的前綴標示,可以如下:
+
+```js
+// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
-// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
-請注意瀏覽器前綴標示的實作可能不完整、有些問題或仍然遵守舊版標準,因此不建議在正式版程式碼中使用。與其宣稱支援又有問題,倒不如直接不支援。
-if (!window.indexedDB) {
+// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
+```
+
+請注意瀏覽器前綴標示的實作可能不完整、有些問題或仍然遵守舊版標準,因此不建議在正式版程式碼中使用。與其宣稱支援又有問題,倒不如直接不支援。
+
+```js
+if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
}
-
-開啟資料庫
-開頭如下:
-// Let us open our database
+```
+
+### 開啟資料庫
+
+開頭如下:
+
+```js
+// Let us open our database
var request = window.indexedDB.open("MyTestDatabase", 3);
-
-注意到了嗎,開啟資料庫必須要進行請求。
-開啟請求並不會立刻開啟資料庫或交易,呼叫open()方法會回傳一個IDBOpenDBRequest
物件,這個物件擁有兩個事件(success和error)。大部分IndexedDB的非同步功能都會回傳一個IDBDatabase
類物件,然後我們可以註冊成功和失敗事件處理器。
-Open方法第二個參數是資料庫版本,資料庫版本決定了資料庫結構,也就是資料庫物件存檔的結構。如果請求版本不存在(比如因為這是一個新資料庫或是資料庫版本已升級),onupgradeneeded事件會被觸發,然後我們可以在onupgradeneeded事件處理器中再建立新的版本,下面升級資料庫版本 有更詳細的說明。
-產生事件處理器
-幾乎所有第一件要對請求做的事都是產生success和error事件處理器:
-request.onerror = function(event) {
+```
+
+注意到了嗎,開啟資料庫必須要進行請求。
+
+開啟請求並不會立刻開啟資料庫或交易,呼叫 open()方法會回傳一個[`IDBOpenDBRequest`](/zh-TW/docs/IndexedDB/IDBOpenDBRequest)物件,這個物件擁有兩個事件(success 和 error)。大部分 IndexedDB 的非同步功能都會回傳一個[`IDBDatabase`](/en-US/docs/IndexedDB/IDBDatabase)類物件,然後我們可以註冊成功和失敗事件處理器。
+
+Open 方法第二個參數是資料庫版本,資料庫版本決定了資料庫結構,也就是資料庫物件存檔的結構。如果請求版本不存在(比如因為這是一個新資料庫或是資料庫版本已升級),onupgradeneeded 事件會被觸發,然後我們可以在 onupgradeneeded 事件處理器中再建立新的版本,下面[升級資料庫版本](#Updating_the_version_of_the_database)有更詳細的說明。
+
+#### 產生事件處理器
+
+幾乎所有第一件要對請求做的事都是產生 success 和 error 事件處理器:
+
+```js
+request.onerror = function(event) {
// Do something with request.errorCode!
};
request.onsuccess = function(event) {
// Do something with request.result!
-};
-如果一切正常,success事件(也就是DOM事件的type屬性設為success)會以request為目標觸發,然後request物件上的onsuccess函數接著被呼叫,其中success事件就是參數;否則error事件(也就是DOM事件的type屬性設為error)會以request為目標觸發,然後request物件上的onerror函數接著被呼叫,其中error事件就是參數。
-IndexedDB的API設計上盡量減少錯誤處理,所以不太常看到錯誤事件,不過開啟資料庫的時候還是有一些狀況會產產生錯誤,最常見的狀況是使用者拒絕我們建立資料庫。
-IndexedDB設計目標之一為存放大量資料以供離線使用(請參考"儲存限制" 了解更多細節)。但很明顯地,瀏覽器又不樂見一些廣告網站或惡意網站汙染電腦,所以當任一個網路應用第一次開啟IndexedDB資料庫,瀏覽器會徵詢使用者是否准許其作業;同時在私密瀏覽中開啟作業也會失敗,因為私密瀏覽不會留下任何瀏覽痕跡。
-這裡呼叫indexedDB.open()開啟indexedDB資料庫並回傳request物件,假設使用者允許我們建立indexedDB資料庫,我們也收到suceess事件觸發了success回呼函數(callback),request物件的result屬性會是一個IDBDatabase物件 ,接下來便是要儲存這個物件之後使用。下方是整個作業的示範程式碼:
-var db;
+};
+```
+
+如果一切正常,success 事件(也就是 DOM 事件的 type 屬性設為 success)會以 request 為目標觸發,然後 request 物件上的 onsuccess 函數接著被呼叫,其中 success 事件就是參數;否則 error 事件(也就是 DOM 事件的 type 屬性設為 error)會以 request 為目標觸發,然後 request 物件上的 onerror 函數接著被呼叫,其中 error 事件就是參數。
+
+IndexedDB 的 API 設計上盡量減少錯誤處理,所以不太常看到錯誤事件,不過開啟資料庫的時候還是有一些狀況會產產生錯誤,最常見的狀況是使用者拒絕我們建立資料庫。
+
+IndexedDB 設計目標之一為存放大量資料以供離線使用(請參考["儲存限制"](/en/IndexedDB#Storage_limits)了解更多細節)。但很明顯地,瀏覽器又不樂見一些廣告網站或惡意網站汙染電腦,所以當任一個網路應用第一次開啟 IndexedDB 資料庫,瀏覽器會徵詢使用者是否准許其作業;同時在私密瀏覽中開啟作業也會失敗,因為私密瀏覽不會留下任何瀏覽痕跡。
+
+這裡呼叫 indexedDB.open()開啟 indexedDB 資料庫並回傳 request 物件,假設使用者允許我們建立 indexedDB 資料庫,我們也收到 suceess 事件觸發了 success 回呼函數(callback),request 物件的 result 屬性會是一個 IDBDatabase 物件 ,接下來便是要儲存這個物件之後使用。下方是整個作業的示範程式碼:
+
+```js
+var db;
var request = indexedDB.open("MyTestDatabase");
request.onerror = function(event) {
alert("Why didn't you allow my web app to use IndexedDB?!");
@@ -66,70 +92,69 @@ request.onerror = function(event) {
request.onsuccess = function(event) {
db = request.result;
};
-
-錯誤處理
-錯誤事件會向上傳遞;錯誤事件以產生錯誤之請求為目標觸發,然後一路傳遞到交易,最後到資料庫物件;如果不想要為每一個請求新增錯誤處理器,可以改為資料庫物件加入一個錯誤處理器。
-db.onerror = function(event) {
+```
+
+#### 錯誤處理
+
+錯誤事件會向上傳遞;錯誤事件以產生錯誤之請求為目標觸發,然後一路傳遞到交易,最後到資料庫物件;如果不想要為每一個請求新增錯誤處理器,可以改為資料庫物件加入一個錯誤處理器。
+
+```js
+db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's
// requests!
alert("Database error: " + event.target.errorCode);
};
-
-最常見的錯誤之一就是VER_ERR,該錯誤代表現在資料料庫版本大於嘗試開啟的資料庫版本,這項錯誤必須要有錯誤處理器處理。
-建立或更新資料庫版本
-新版本資料庫建立會觸發onupgradeneeded事件,在這個事件的處理器中要建立這個版本資料庫需要的物件存檔。
-// This event is only implemented in recent browsers
+```
+
+最常見的錯誤之一就是 VER_ERR,該錯誤代表現在資料料庫版本大於嘗試開啟的資料庫版本,這項錯誤必須要有錯誤處理器處理。
+
+### 建立或更新資料庫版本
+
+新版本資料庫建立會觸發 onupgradeneeded 事件,在這個事件的處理器中要建立這個版本資料庫需要的物件存檔。
+
+```js
+// This event is only implemented in recent browsers
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an objectStore for this database
var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
-};
-資料庫版本是unsigned long long的數字,所以能夠非常長。
-
-
請注意這也意味著版本不能為浮點數,否則小數點部分將會無條件捨去,而交易也可能不會開始,upgradeneeded事件也不會觸發。不要像以下例子以2.4作版本:
-
var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2
-
-升級版本資料庫建立會觸發onupgradeneeded事件,這個時候資料庫裡面已經含有前版本下的物件存檔,所以說不需要再次建立這些物件存檔了,剩下的是新增或刪除物件存檔。如果想要更動既存物件存檔(例如改變資料鍵路徑),那麼會需要先刪除舊的再產生一個新的(請注意這也會刪除物件存檔裡的資料,所以如果資料需要保留的話,請在升級前先讀出資料備份。)
-Webkit支援最新標準不過只有Chrome 23才開始導入,而較舊不支援最新版標準的版本則不支援indexedDB.open(name, version).onupgradeneeded。關於如何在舊版標準下升級資料庫版本請參考"IDBDatabase參考文章" 。
-結構化資料庫
-indexedDB不用資料表而是物件存檔,物件存檔可以有很多。一筆物件存檔裡的資料值對應一筆資料鍵,依據使用{資料鍵路徑(key path )}或{資料鍵產生器(key generator )}。
-下表列出資料建各類產生途徑:
-
-
-
- Key Path
- Key Generator
- 描述
-
-
-
-
- No
- No
- 物件存檔資料值能為任何型別,即使像數字或字串。每當新增一筆資料,必須提供不同的資料鍵。
-
-
- Yes
- No
- 物件存檔資料值僅能為Javacript物件,而該資料物件必須含有和資料鍵路徑相同名稱之屬性成員。
-
-
- No
- Yes
- 物件存檔資料值能為任何型別,資料鍵自動產生,但如果想要指定資料鍵也可以另外提供資料鍵。
-
-
- Yes
- Yes
- 物件存檔資料值僅能為Javascript物件。通常被產生的新資料鍵的值會被存在物件屬性名稱和資料鍵路徑名稱相同的物件屬性下,如果這個屬性已經存在,這個已經存在之屬性之值將被用作為資料鍵,而非新產生的資料鍵。
-
-
-
-我們可以替任何儲存資料為物件型態而非原始資料型態的物件存檔建立索引,索引讓我們能夠用物件存檔中資料物件內的某一個屬性值查找資料,而非僅僅物件的資料鍵。
-除此之外,利用索引還可以施加簡單的儲存限制;建立索引時設定獨特旗標(flag),這個索引保證在此索引資料鍵下不會存在兩個物件存檔擁有同樣資料值,比如說現在有一個存放許多使用者的物件存檔,而且我們希望保證不會存在有兩個使用者的電子郵件地址一樣,此使索引的獨特旗標便可以幫助我們達成目標。
-以上聽起來可能會有些複雜,請看一下下面的實例:
-// This is what our customer data looks like.
+};
+```
+
+資料庫版本是 unsigned long long 的數字,所以能夠非常長。
+
+> **警告:** 請注意這也意味著版本不能為浮點數,否則小數點部分將會無條件捨去,而交易也可能不會開始,upgradeneeded 事件也不會觸發。不要像以下例子以 2.4 作版本:
+>
+> ```js
+> var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2
+> ```
+
+升級版本資料庫建立會觸發 onupgradeneeded 事件,這個時候資料庫裡面已經含有前版本下的物件存檔,所以說不需要再次建立這些物件存檔了,剩下的是新增或刪除物件存檔。如果想要更動既存物件存檔(例如改變資料鍵路徑),那麼會需要先刪除舊的再產生一個新的(請注意這也會刪除物件存檔裡的資料,所以如果資料需要保留的話,請在升級前先讀出資料備份。)
+
+Webkit 支援最新標準不過只有 Chrome 23 才開始導入,而較舊不支援最新版標準的版本則不支援 indexedDB.open(name, version).onupgradeneeded。關於如何在舊版標準下升級資料庫版本請參考["IDBDatabase 參考文章"](/zh-TW/docs/Web/API/IDBDatabase?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBDatabase#setVersion%28%29_.0A.0ADeprecated)。
+
+### 結構化資料庫
+
+indexedDB 不用資料表而是物件存檔,物件存檔可以有很多。一筆物件存檔裡的資料值對應一筆資料鍵,依據使用{資料鍵路徑([key path](/en/IndexedDB#gloss_key_path))}或{資料鍵產生器([key generator](/en/IndexedDB#gloss_key_generator))}。
+
+下表列出資料建各類產生途徑:
+
+| Key Path | Key Generator | 描述 |
+| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| No | No | 物件存檔資料值能為任何型別,即使像數字或字串。每當新增一筆資料,必須提供不同的資料鍵。 |
+| Yes | No | 物件存檔資料值僅能為 Javacript 物件,而該資料物件必須含有和資料鍵路徑相同名稱之屬性成員。 |
+| No | Yes | 物件存檔資料值能為任何型別,資料鍵自動產生,但如果想要指定資料鍵也可以另外提供資料鍵。 |
+| Yes | Yes | 物件存檔資料值僅能為 Javascript 物件。通常被產生的新資料鍵的值會被存在物件屬性名稱和資料鍵路徑名稱相同的物件屬性下,如果這個屬性已經存在,這個已經存在之屬性之值將被用作為資料鍵,而非新產生的資料鍵。 |
+
+我們可以替任何儲存資料為物件型態而非原始資料型態的物件存檔建立索引,索引讓我們能夠用物件存檔中資料物件內的某一個屬性值查找資料,而非僅僅物件的資料鍵。
+
+除此之外,利用索引還可以施加簡單的儲存限制;建立索引時設定獨特旗標(flag),這個索引保證在此索引資料鍵下不會存在兩個物件存檔擁有同樣資料值,比如說現在有一個存放許多使用者的物件存檔,而且我們希望保證不會存在有兩個使用者的電子郵件地址一樣,此使索引的獨特旗標便可以幫助我們達成目標。
+
+以上聽起來可能會有些複雜,請看一下下面的實例:
+
+```js
+// This is what our customer data looks like.
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
@@ -162,17 +187,26 @@ request.onupgradeneeded = function(event) {
objectStore.add(customerData[i]);
}
};
-
-請注意onupgradeneeded事件是唯一能夠變更資料庫結構之處,在此事件才能建立或刪除物件存檔以及建立和刪除索引。
-
- 呼叫
IDBDatabase 類別物件的createObjectStore方法會立刻創造一個物件存檔,這個方法接收兩個參數,一個是物件存檔名稱,一個是非必填的參數物件,雖然參數物件不為必填但是卻相當重要,因為它讓我們定義了一些重要屬性(請參考
createObjectStore )。本例中我們要求建立了一個"customer"物件存檔,定義"ssn"屬性為資料件路徑,使用"ssn"作為資料鍵路徑是因為每個客戶的ssn碼一定是獨立的。一旦決定了"ssn"作為資料鍵路徑,那麼每一筆資料一定要含有"ssn"。
-本例還創建一個稱為"name"的索引,"name"索引查找目標為資料的"name"屬性,且不設立其獨特旗標(unique為false),同樣地,我們又呼叫createIndex 方法創建了一個"email"索引,不過"email"索引具備獨特旗標(unique為true)。雖然存在"name"索引,但資料不一定要含有"name"屬性,只是當搜索"name"索引時資料不會出現。
-接下來我們可以開始用ssn從物件存檔中取出資料,或是用索引找出資料(請參考使用索引 )。
-使用資料鍵產生器
-當建立物件存檔時設定autoIncrement旗標為ture將啟動資料鍵產生器,預設上該旗標為false。
-有了資料鍵產生器,當新增資料到物件存檔中,資料鍵產生器會自動幫我們產生資料鍵。資料鍵產生器產生的資料鍵由整數1開始,而基本上新產生的資料鍵是由前一個資料鍵加1產生。資料鍵的產生不會因為資料刪除或清空所有資料而重新開始起算,所以資料鍵值是一直累加上去的,除非資料庫操作中斷,整個交易作業被取消。
-我們可以建立一個有資料鍵產生器的物件存檔如下:
-// Open the indexedDB.
+```
+
+請注意 onupgradeneeded 事件是唯一能夠變更資料庫結構之處,在此事件才能建立或刪除物件存檔以及建立和刪除索引。
+
+呼叫[IDBDatabase](/zh-TW/docs/Web/API/IDBDatabase?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBDatabase#setVersion%28%29_.0A.0ADeprecated)類別物件的 createObjectStore 方法會立刻創造一個物件存檔,這個方法接收兩個參數,一個是物件存檔名稱,一個是非必填的參數物件,雖然參數物件不為必填但是卻相當重要,因為它讓我們定義了一些重要屬性(請參考[createObjectStore](/zh-TW/docs/Web/API/IDBDatabase?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBDatabase#createObjectStore))。本例中我們要求建立了一個"customer"物件存檔,定義"ssn"屬性為資料件路徑,使用"ssn"作為資料鍵路徑是因為每個客戶的 ssn 碼一定是獨立的。一旦決定了"ssn"作為資料鍵路徑,那麼每一筆資料一定要含有"ssn"。
+
+本例還創建一個稱為"name"的索引,"name"索引查找目標為資料的"name"屬性,且不設立其獨特旗標(unique 為 false),同樣地,我們又呼叫[createIndex]()方法創建了一個"email"索引,不過"email"索引具備獨特旗標(unique 為 true)。雖然存在"name"索引,但資料不一定要含有"name"屬性,只是當搜索"name"索引時資料不會出現。
+
+接下來我們可以開始用 ssn 從物件存檔中取出資料,或是用索引找出資料(請參考[使用索引](/zh-TW/docs/IndexedDB/Using_IndexedDB#.E4.BD.BF.E7.94.A8.E7.B4.A2.E5.BC.95))。
+
+### 使用資料鍵產生器
+
+當建立物件存檔時設定 autoIncrement 旗標為 ture 將啟動資料鍵產生器,預設上該旗標為 false。
+
+有了資料鍵產生器,當新增資料到物件存檔中,資料鍵產生器會自動幫我們產生資料鍵。資料鍵產生器產生的資料鍵由整數 1 開始,而基本上新產生的資料鍵是由前一個資料鍵加 1 產生。資料鍵的產生不會因為資料刪除或清空所有資料而重新開始起算,所以資料鍵值是一直累加上去的,除非資料庫操作中斷,整個交易作業被取消。
+
+我們可以建立一個有資料鍵產生器的物件存檔如下:
+
+```js
+// Open the indexedDB.
var request = indexedDB.open(dbName, 3);
request.onupgradeneeded = function (event) {
@@ -183,26 +217,41 @@ request.onupgradeneeded = function (event) {
// Because the "names" object store has the key generator, the key for the name value is generated automatically.
// The added records would be like:
- // key : 1 => value : "Bill"
- // key : 2 => value : "Donna"
+ // key : 1 => value : "Bill"
+ // key : 2 => value : "Donna"
for (var i in customerData) {
objStore.add(customerData[i].name);
}
-}
-關於資料鍵產生器細節,請參考"W3C Key Generators" 。
-新增和刪除資料
-在操作資料庫之前必須要先進行交易,交易來自資料庫物件,在交易中要指定涵蓋物件存檔範圍,然後也要決定是要變更資料庫或純粹讀取資料。交易共有三種種類,分別是讀取(read-only),讀寫(read/write), 以及版本變更(versionchange),如果只需要讀資料最好只使用讀取(read-only)交易,因為讀取(read-only)交易可以多重同步進行。
-新增資料到資料庫
-創建資料庫後,如果要寫入資料請這麼做:
-var transaction = db.transaction(["customers"], "readwrite");
+}
+```
+
+關於資料鍵產生器細節,請參考["W3C Key Generators"](http://www.w3.org/TR/IndexedDB/#key-generator-concept)。
+
+## 新增和刪除資料
+
+在操作資料庫之前必須要先進行交易,交易來自資料庫物件,在交易中要指定涵蓋物件存檔範圍,然後也要決定是要變更資料庫或純粹讀取資料。交易共有三種種類,分別是讀取(read-only),讀寫(read/write), 以及版本變更(versionchange),如果只需要讀資料最好只使用讀取(read-only)交易,因為讀取(read-only)交易可以多重同步進行。
+
+### 新增資料到資料庫
+
+創建資料庫後,如果要寫入資料請這麼做:
+
+```js
+var transaction = db.transaction(["customers"], "readwrite");
// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
// In case you want to support such an implementation, you can just write:
-// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
-呼叫transaction() 方法會回傳一個交易物件。transaction()第一個接受參數代表交易涵蓋的物件存檔,雖然傳入空陣列會讓交易涵蓋所有物件存檔,但請不要這麼做,因為根據正式標準傳入空陣列應該要導致InvalidAccessError錯誤;第二個參數代表交易種類,不傳入的話預設為讀取交易,本例要寫入資料庫所以傳入讀寫("readwrite")。
-交易的生命週期和事件循環關係密切。當我們發起交易又回到事件循環中後,如果忽略,那麼交易將轉成結束,唯一保持交易存活的方法是在交易上發出請求;當請求完成後我們會收到DOM事件,假設請求結果成功,我們可以在事件的回呼函數(callback中)繼續進行交易,反之,如果我們沒有繼續進行交易,那麼交易將結束,也就是說只要尚有未完成請求的話,交易就會繼續存活,如果收到TRANSACTION_INACTIVE_ERR錯誤那便意謂著交易早已結束,我們錯過了繼續進行交易的機會。
-交易能收到三種事件: 錯誤(error)、中斷(abort)以及完成(complete),其中錯誤事件會向上傳遞,所以任何一個交易下轄的請求產生錯誤事件,該交易都會收到。如果交易收到錯誤事件時,瀏覽器預設行為會中斷交易,除非我們有在錯誤事件上呼叫preventDefault()阻擋瀏覽器預設行動,否則整筆交易都將取消、復原,這樣的設計告訴我們必須要思考如何處裡錯誤,或者說如果對每一個錯誤進行處裡過於麻煩,那麼至少加入一個概括性的錯誤處理器也是可以。只要不處裡錯誤或呼叫abort(),交易將取消、復原,然後中斷事件接著觸發,反之,當所有請求都完成後,我們會收到一個完成事件,所以說如果我們同時發起多項請求時,可以只追蹤單一交易而非個別請求,這樣會大大減輕我們的負擔。
-有了交易之後便能夠從中取得物件存檔,有了物件存檔便能夠新增資料(請注意唯有在建立交易時指定的物件存檔能夠取得)。
-// Do something when all the data is added to the database.
+// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
+```
+
+呼叫[transaction()](/zh-TW/docs/Web/API/IDBDatabase#transaction)方法會回傳一個交易物件。transaction()第一個接受參數代表交易涵蓋的物件存檔,雖然傳入空陣列會讓交易涵蓋所有物件存檔,但請不要這麼做,因為根據正式標準傳入空陣列應該要導致 InvalidAccessError 錯誤;第二個參數代表交易種類,不傳入的話預設為讀取交易,本例要寫入資料庫所以傳入讀寫("readwrite")。
+
+交易的生命週期和事件循環關係密切。當我們發起交易又回到事件循環中後,如果忽略,那麼交易將轉成結束,唯一保持交易存活的方法是在交易上發出請求;當請求完成後我們會收到 DOM 事件,假設請求結果成功,我們可以在事件的回呼函數(callback 中)繼續進行交易,反之,如果我們沒有繼續進行交易,那麼交易將結束,也就是說只要尚有未完成請求的話,交易就會繼續存活,如果收到 TRANSACTION_INACTIVE_ERR 錯誤那便意謂著交易早已結束,我們錯過了繼續進行交易的機會。
+
+交易能收到三種事件: 錯誤(error)、中斷(abort)以及完成(complete),其中錯誤事件會向上傳遞,所以任何一個交易下轄的請求產生錯誤事件,該交易都會收到。如果交易收到錯誤事件時,瀏覽器預設行為會中斷交易,除非我們有在錯誤事件上呼叫 preventDefault()阻擋瀏覽器預設行動,否則整筆交易都將取消、復原,這樣的設計告訴我們必須要思考如何處裡錯誤,或者說如果對每一個錯誤進行處裡過於麻煩,那麼至少加入一個概括性的錯誤處理器也是可以。只要不處裡錯誤或呼叫 abort(),交易將取消、復原,然後中斷事件接著觸發,反之,當所有請求都完成後,我們會收到一個完成事件,所以說如果我們同時發起多項請求時,可以只追蹤單一交易而非個別請求,這樣會大大減輕我們的負擔。
+
+有了交易之後便能夠從中取得物件存檔,有了物件存檔便能夠新增資料(請注意唯有在建立交易時指定的物件存檔能夠取得)。
+
+```js
+// Do something when all the data is added to the database.
transaction.oncomplete = function(event) {
alert("All done!");
};
@@ -217,19 +266,30 @@ for (var i in customerData) {
request.onsuccess = function(event) {
// event.target.result == customerData[i].ssn;
};
-}
-呼叫add 方法可以加入一筆新資料,呼叫後會回傳一個IDBRequest 物件,即為上方範例中的request,如果新增成功,request的成功事件會被觸發,而成功事件物件中有一個result屬性,這個result值剛好就等於新資料的資料鍵,所以說上方範例中的event.target.result剛好就等於顧客的ssn值(因為我們用ssn屬性作為資料鍵路徑)。請注意add方法只在當物件存檔中沒有相同資料鍵資料存在時有用,如果想要更動或是直接覆蓋現存資料請呼叫put 方法。
-移除資料
-移除資料十分容易:
-var request = db.transaction(["customers"], "readwrite")
+}
+```
+
+呼叫[add]()方法可以加入一筆新資料,呼叫後會回傳一個[IDBRequest](/zh-TW/docs/Web/API/IDBRequest?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBRequest)物件,即為上方範例中的 request,如果新增成功,request 的成功事件會被觸發,而成功事件物件中有一個 result 屬性,這個 result 值剛好就等於新資料的資料鍵,所以說上方範例中的 event.target.result 剛好就等於顧客的 ssn 值(因為我們用 ssn 屬性作為資料鍵路徑)。請注意 add 方法只在當物件存檔中沒有相同資料鍵資料存在時有用,如果想要更動或是直接覆蓋現存資料請呼叫[put]()方法。
+
+## 移除資料
+
+移除資料十分容易:
+
+```js
+var request = db.transaction(["customers"], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = function(event) {
// It's gone!
-};
-讀取資料
-要圖取資料庫內的資料有數種途徑,第一個最簡單的途徑就是提供資料鍵,呼叫get 方法取得資料:
-var transaction = db.transaction(["customers"]);
+};
+```
+
+## 讀取資料
+
+要圖取資料庫內的資料有數種途徑,第一個最簡單的途徑就是提供資料鍵,呼叫[get]()方法取得資料:
+
+```js
+var transaction = db.transaction(["customers"]);
var objectStore = transaction.objectStore("customers");
var request = objectStore.get("444-44-4444");
request.onerror = function(event) {
@@ -238,15 +298,25 @@ request.onerror = function(event) {
request.onsuccess = function(event) {
// Do something with the request.result!
alert("Name for SSN 444-44-4444 is " + request.result.name);
-};
-假設我們把錯誤處理放在資料庫層級,我們可以再縮短上面的程式碼如下:
-db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
+};
+```
+
+假設我們把錯誤處理放在資料庫層級,我們可以再縮短上面的程式碼如下:
+
+```js
+db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
alert("Name for SSN 444-44-4444 is " + event.target.result.name);
-};
-呼叫transcation方法而不指定模式會開啟讀取(readonly)模式,接著取得我們的目標物件存檔,輸入目標資料的資料鍵,呼叫get方法取得請求物件,然後在請求物件上註冊成功事件處理器,當作業成功後,成功事件會觸發,成功事件的物件中含有請求物件(event.target如上述範例),請求物件中含有請求結果(event.target.result如上述範例)。
-使用指標(Cursor)
-使用get方法需要知道資料鍵,如果想要一一存取物件存檔中的資料,我們可以利用指標:
-var objectStore = db.transaction("customers").objectStore("customers");
+};
+```
+
+呼叫 transcation 方法而不指定模式會開啟讀取(readonly)模式,接著取得我們的目標物件存檔,輸入目標資料的資料鍵,呼叫 get 方法取得請求物件,然後在請求物件上註冊成功事件處理器,當作業成功後,成功事件會觸發,成功事件的物件中含有請求物件(event.target 如上述範例),請求物件中含有請求結果(event.target.result 如上述範例)。
+
+## 使用指標(Cursor)
+
+使用 get 方法需要知道資料鍵,如果想要一一存取物件存檔中的資料,我們可以利用指標:
+
+```js
+var objectStore = db.transaction("customers").objectStore("customers");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
@@ -257,10 +327,15 @@ objectStore.openCursor().onsuccess = function(event) {
else {
alert("No more entries!");
}
-};
-openCursor 方法第一個參數用來接受資料鍵範圍物件來限制存取資料範圍,第二個參數用來指定存取進行方向,像上面的範例程式便是以資料鍵由小到大之方向存取資料;呼叫openCursor方法後一樣會回傳一個請求物件,成功時成功事件會觸發,不過這裡有些地方要特別注意,當成功事件處裡函數被喚起時,指標物件(cursor)會存放在result屬性內(亦即上述event.target.result),cursor物件下有兩個屬性,key屬性是資料鍵,value屬性是資料值,如果要取得下一份資料就呼叫cursor的continue()方法,然後cursor物件就會指向下一份資料,當沒有資料時,cursor會是undefined,當請求一開始便找沒有資料,result屬性也會是undefined。
-以下用cursor存取一遍資料後放在陣列中的作法相當常見:
-var customers = [];
+};
+```
+
+[openCursor]()方法第一個參數用來接受資料鍵範圍物件來限制存取資料範圍,第二個參數用來指定存取進行方向,像上面的範例程式便是以資料鍵由小到大之方向存取資料;呼叫 openCursor 方法後一樣會回傳一個請求物件,成功時成功事件會觸發,不過這裡有些地方要特別注意,當成功事件處裡函數被喚起時,指標物件(cursor)會存放在 result 屬性內(亦即上述 event.target.result),cursor 物件下有兩個屬性,key 屬性是資料鍵,value 屬性是資料值,如果要取得下一份資料就呼叫 cursor 的 continue()方法,然後 cursor 物件就會指向下一份資料,當沒有資料時,cursor 會是 undefined,當請求一開始便找沒有資料,result 屬性也會是 undefined。
+
+以下用 cursor 存取一遍資料後放在陣列中的作法相當常見:
+
+```js
+var customers = [];
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
@@ -271,23 +346,38 @@ objectStore.openCursor().onsuccess = function(event) {
else {
alert("Got all customers: " + customers);
}
-};
-
- Warning: 以下範例不是IndexedDB標準!
-Mozilla瀏覽器自己做了一個getAll()方法來方便一次取得所有cursor下的資料值,這個方法相當方便,不過請小心未來它有可能會消失。以下程式碼的效果和上面的一樣:
-objectStore.getAll().onsuccess = function(event) {
+};
+```
+
+> **警告:** 以下範例不是 IndexedDB 標準!
+
+Mozilla 瀏覽器自己做了一個 getAll()方法來方便一次取得所有 cursor 下的資料值,這個方法相當方便,不過請小心未來它有可能會消失。以下程式碼的效果和上面的一樣:
+
+```js
+objectStore.getAll().onsuccess = function(event) {
alert("Got all customers: " + event.target.result);
-};
-一一檢查cursor的value屬性較不利性能表現,因為物件是被動一一建立,然而呼叫getAll(),Gecko一定要一次建立所有物件,所以如果想要一次取得所有物件的資料值陣列使用getAll()比較好,如果想要一一檢查每筆資料則請利用cursor的方法。
-使用索引
-利用一定唯一的ssn碼作為資料鍵相當合乎邏輯(隱私權的問題先擱置一放,不在本文探討範圍)。不過當我們想要查詢使用者的名字的時候,如果沒有索引就需要一一檢查每一筆資料,十分沒有效率,所以我們可以建立name的索引。
-var index = objectStore.index("name");
+};
+```
+
+一一檢查 cursor 的 value 屬性較不利性能表現,因為物件是被動一一建立,然而呼叫 getAll(),Gecko 一定要一次建立所有物件,所以如果想要一次取得所有物件的資料值陣列使用 getAll()比較好,如果想要一一檢查每筆資料則請利用 cursor 的方法。
+
+### 使用索引
+
+利用一定唯一的 ssn 碼作為資料鍵相當合乎邏輯(隱私權的問題先擱置一放,不在本文探討範圍)。不過當我們想要查詢使用者的名字的時候,如果沒有索引就需要一一檢查每一筆資料,十分沒有效率,所以我們可以建立 name 的索引。
+
+```js
+var index = objectStore.index("name");
index.get("Donna").onsuccess = function(event) {
alert("Donna's SSN is " + event.target.result.ssn);
-};
-因為name不是唯一值,所以可能會有多筆資料符合"Donna"名字,此時呼叫get()會取得資料鍵最小值的資料。
-如果我們想要查看特定名字下所有的資料,可以利用cursor。有兩種cursor能用在索引上,第一種一般cursor會比對索引值並回傳整份資料(物件存檔中的物件),第二種資料鍵cursor則只會回傳資料鍵值,請參考下方範例比較兩者差異:
-index.openCursor().onsuccess = function(event) {
+};
+```
+
+因為 name 不是唯一值,所以可能會有多筆資料符合"Donna"名字,此時呼叫 get()會取得資料鍵最小值的資料。
+
+如果我們想要查看特定名字下所有的資料,可以利用 cursor。有兩種 cursor 能用在索引上,第一種一般 cursor 會比對索引值並回傳整份資料(物件存檔中的物件),第二種資料鍵 cursor 則只會回傳資料鍵值,請參考下方範例比較兩者差異:
+
+```js
+index.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// cursor.key is a name, like "Bill", and cursor.value is the whole object.
@@ -304,10 +394,15 @@ index.openKeyCursor().onsuccess = function(event) {
alert("Name: " + cursor.key + ", SSN: " + cursor.value);
cursor.continue();
}
-};
-設定指標查詢範圍和方向
-如果想要限定指標查詢範圍,那麼在乎叫openCursor()或openKeyCursor()時第一個參數要傳入IDBKeyRange 物件以限制範圍。IDBKeyRange物件能夠只聚焦在單一資料鍵上或者一段上下限區間;上下限區間可以是封閉(含界限)或開放(不含界限),請看以下範例:
-// Only match "Donna"
+};
+```
+
+### 設定指標查詢範圍和方向
+
+如果想要限定指標查詢範圍,那麼在乎叫 openCursor()或 openKeyCursor()時第一個參數要傳入[IDBKeyRange](/en/IndexedDB/IDBKeyRange)物件以限制範圍。IDBKeyRange 物件能夠只聚焦在單一資料鍵上或者一段上下限區間;上下限區間可以是封閉(含界限)或開放(不含界限),請看以下範例:
+
+```js
+// Only match "Donna"
var singleKeyRange = IDBKeyRange.only("Donna");
// Match anything past "Bill", including "Bill"
@@ -328,27 +423,41 @@ index.openCursor(boundKeyRange).onsuccess = function(event) {
// Do something with the matches.
cursor.continue();
}
-};
-有時候我們會想要由大到小查看資料而非預設由小到大方向,傳入第二個"prev"字串便能做到:
-objectStore.openCursor(null, "prev").onsuccess = function(event) {
+};
+```
+
+有時候我們會想要由大到小查看資料而非預設由小到大方向,傳入第二個"prev"字串便能做到:
+
+```js
+objectStore.openCursor(null, "prev").onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
-};
-由於"name"索引不具唯一性,所以一個名字下可能會出現多筆資料,此時如果想要避開這多筆資料,請傳入"nextunique"或"prevunique"做為第二個方向參數,當傳入之後,如一個名字下遇到多筆資料,則只有資料鍵最小的資料會被回傳。
-index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
+};
+```
+
+由於"name"索引不具唯一性,所以一個名字下可能會出現多筆資料,此時如果想要避開這多筆資料,請傳入"nextunique"或"prevunique"做為第二個方向參數,當傳入之後,如一個名字下遇到多筆資料,則只有資料鍵最小的資料會被回傳。
+
+```js
+index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
-};
-關於可傳入的方向參數,請參考IDBCursor 常數。
-當網頁應用程式於瀏覽器另一個分頁開啟時變更版本
-請思考以下狀況: 使用者在第一個瀏覽器分頁中使用著舊版本,然後使用者又打開第二個分頁載入網頁,此時我們在新分頁需要對資料庫進行升級,所以呼叫open()以更新版本開啟資料庫,但是由於第一個瀏覽器分頁並沒有關閉資料庫,因此第二個分頁的資料庫升級作業會被擋住。所以我們需要注意多個分頁同時開啟的狀況,每個分頁都得注意當發生資料庫升級事件時,要記得關閉資料庫,讓資料庫升級作業得以進行。實際作法如下:
-var openReq = mozIndexedDB.open("MyTestDatabase", 2);
+};
+```
+
+關於可傳入的方向參數,請參考[IDBCursor](/zh-TW/docs/Web/API/IDBCursor?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBCursor#Constants)常數。
+
+## 當網頁應用程式於瀏覽器另一個分頁開啟時變更版本
+
+請思考以下狀況: 使用者在第一個瀏覽器分頁中使用著舊版本,然後使用者又打開第二個分頁載入網頁,此時我們在新分頁需要對資料庫進行升級,所以呼叫 open()以更新版本開啟資料庫,但是由於第一個瀏覽器分頁並沒有關閉資料庫,因此第二個分頁的資料庫升級作業會被擋住。所以我們需要注意多個分頁同時開啟的狀況,每個分頁都得注意當發生資料庫升級事件時,要記得關閉資料庫,讓資料庫升級作業得以進行。實際作法如下:
+
+```js
+var openReq = mozIndexedDB.open("MyTestDatabase", 2);
openReq.onblocked = function(event) {
// If some other tab is loaded with the database, then it needs to be closed
@@ -379,151 +488,165 @@ function useDatabase(db) {
// Do stuff with the database.
}
-
-安全性
-IndexedDB遵守同源政策 ,所以它綁定創建它的來源網站,其他來源網站無法存取。
- 就像對載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁的第三方cookie所設下的安全性和隱私權考量限制,IndexedDB無法在載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁上運作,詳情請見{{ bug(595307) }}。
-瀏覽器關閉風險
-當瀏覽器關閉,例如使用者按下關閉鈕,任何未完成IndexedDB交易都將默默中止,這些交易不會完成,錯誤事件也不會觸發。既然瀏覽器可能隨時被關閉,我們無法完全指望任何特定交易一定會完成,或是依賴錯誤事件做出相應處理,針對這種狀況,我們需要注意:
-第一、每一筆交易結束後都應該要保持資料庫完整性,例如說,有一串使用者編輯項目清單正要存入資料庫,我們如果先在一個交易中清除舊清單,然後在另一個交易中存入新清單,那就會面臨到清除完就清單後,新清單存入交易還來不及回存,瀏覽器就關閉的風險,而這個時候資料庫裡面的清單資料將消失。所以比較好的做法應該是在同一筆交易中完成清除舊清單和存入新清單。
-第二、永遠不要在unload事件中執行資料庫交易,因為如果unload事件是觸發在瀏覽器關閉下,任何資料庫交易都不會發生,或許,瀏覽器(或分頁)打開時讀取資料庫,更新資料庫當使用者編輯資料,當瀏覽器(或分頁)關閉時儲存資料這樣的做法比較直覺,不過資料庫的操作是非同步進行地,所以瀏覽器關閉的執行會在資料庫操作前發生,進而中斷後續非同步的資料庫交易,所以在unload事件中執行資料庫交易是行不通地。
-事實上不論瀏覽器是否正常關閉,都沒有任何方法保證IndexedDB交易能夠順利完成,請見{{ bug(870645) }}。
-完整IndexedDB範例
-HTML
-<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
-
- <h1>IndexedDB Demo: storing blobs, e-publication example</h1>
- <div class="note">
- <p>
+```
+
+## 安全性
+
+IndexedDB 遵守[同源政策](/zh-TW/docs/Web/JavaScript/Same_origin_policy_for_JavaScript),所以它綁定創建它的來源網站,其他來源網站無法存取。
+就像對載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁的第三方 cookie 所設下的安全性和隱私權考量限制,IndexedDB 無法在載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁上運作,詳情請見{{ bug(595307) }}。
+
+## 瀏覽器關閉風險
+
+當瀏覽器關閉,例如使用者按下關閉鈕,任何未完成 IndexedDB 交易都將默默中止,這些交易不會完成,錯誤事件也不會觸發。既然瀏覽器可能隨時被關閉,我們無法完全指望任何特定交易一定會完成,或是依賴錯誤事件做出相應處理,針對這種狀況,我們需要注意:
+
+第一、每一筆交易結束後都應該要保持資料庫完整性,例如說,有一串使用者編輯項目清單正要存入資料庫,我們如果先在一個交易中清除舊清單,然後在另一個交易中存入新清單,那就會面臨到清除完就清單後,新清單存入交易還來不及回存,瀏覽器就關閉的風險,而這個時候資料庫裡面的清單資料將消失。所以比較好的做法應該是在同一筆交易中完成清除舊清單和存入新清單。
+
+第二、永遠不要在 unload 事件中執行資料庫交易,因為如果 unload 事件是觸發在瀏覽器關閉下,任何資料庫交易都不會發生,或許,瀏覽器(或分頁)打開時讀取資料庫,更新資料庫當使用者編輯資料,當瀏覽器(或分頁)關閉時儲存資料這樣的做法比較直覺,不過資料庫的操作是非同步進行地,所以瀏覽器關閉的執行會在資料庫操作前發生,進而中斷後續非同步的資料庫交易,所以在 unload 事件中執行資料庫交易是行不通地。
+
+事實上不論瀏覽器是否正常關閉,都沒有任何方法保證 IndexedDB 交易能夠順利完成,請見{{ bug(870645) }}。
+
+## 完整 IndexedDB 範例
+
+### HTML
+
+```html
+
+
+ IndexedDB Demo: storing blobs, e-publication example
+
+
Works and tested with:
- </p>
- <div id="compat">
- </div>
- </div>
-
- <div id="msg">
- </div>
-
- <form id="register-form">
- <table>
- <tbody>
- <tr>
- <td>
- <label for="pub-title" class="required">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+### CSS
+
+```css
+body {
font-size: 0.8em;
font-family: Sans-Serif;
}
@@ -608,20 +731,22 @@ input {
.destructive:active {
background-color: red;
}
-
-
-JavaScript
-(function () {
+```
+
+### JavaScript
+
+```js
+(function () {
var COMPAT_ENVS = [
- ['Firefox', ">= 16.0"],
+ ['Firefox', ">= 16.0"],
['Google Chrome',
- ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
+ ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
];
var compat = $('#compat');
compat.empty();
- compat.append('<ul id="compat-list"></ul>');
+ compat.append(' ');
COMPAT_ENVS.forEach(function(val, idx, array) {
- $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>');
+ $('#compat-list').append('' + val[0] + ': ' + val[1] + ' ');
});
const DB_NAME = 'mdn-demo-indexeddb-epublications';
@@ -712,8 +837,8 @@ input {
// Thus the count text below will be displayed before the actual pub list
// (not that it is algorithmically important in this case).
req.onsuccess = function(evt) {
- pub_msg.append('<p>There are <strong>' + evt.target.result +
- '</strong> record(s) in the object store.</p>');
+ pub_msg.append('There are ' + evt.target.result +
+ ' record(s) in the object store.
');
};
req.onerror = function(evt) {
console.error("add error", this.error);
@@ -731,17 +856,17 @@ input {
req = store.get(cursor.key);
req.onsuccess = function (evt) {
var value = evt.target.result;
- var list_item = $('<li>' +
+ var list_item = $('' +
'[' + cursor.key + '] ' +
'(biblioid: ' + value.biblioid + ') ' +
value.title +
- '</li>');
+ ' ');
if (value.year != null)
list_item.append(' - ' + value.year);
- if (value.hasOwnProperty('blob') &&
+ if (value.hasOwnProperty('blob') &&
typeof value.blob != 'undefined') {
- var link = $('<a href="' + cursor.key + '">File</a>');
+ var link = $('File ');
link.on('click', function() { return false; });
link.on('mouseenter', function(evt) {
setInViewer(evt.target.getAttribute('href')); });
@@ -767,7 +892,7 @@ input {
function newViewerFrame() {
var viewer = $('#pub-viewer');
viewer.empty();
- var iframe = $('<iframe />');
+ var iframe = $('');
viewer.append(iframe);
return iframe;
}
@@ -799,7 +924,7 @@ input {
} else if (blob.type.indexOf('image/') == 0) {
iframe.load(function() {
var img_id = 'image-' + key;
- var img = $('<img id="' + img_id + '"/>');
+ var img = $(' ');
$(this).contents().find('body').html(img);
var obj_url = window.URL.createObjectURL(blob);
$(this).contents().find('#' + img_id).attr('src', obj_url);
@@ -969,11 +1094,11 @@ input {
function displayActionSuccess(msg) {
msg = typeof msg != 'undefined' ? "Success: " + msg : "Success";
- $('#msg').html('<span class="action-success">' + msg + '</span>');
+ $('#msg').html('' + msg + ' ');
}
function displayActionFailure(msg) {
msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure";
- $('#msg').html('<span class="action-failure">' + msg + '</span>');
+ $('#msg').html('' + msg + ' ');
}
function resetActionStatus() {
console.log("resetActionStatus ...");
@@ -1059,31 +1184,34 @@ input {
addEventListeners();
})(); // Immediately-Invoked Function Expression (IIFE)
-
-{{ LiveSampleLink('Full_IndexedDB_example', "線上範例") }}
-下一步
-請參考IndexedDB文件 ,看看有甚麼IndexedDB API可供使用,實際試玩一下吧。
-延伸閱讀
-參照
-
-相關教學
-
-相關文章
-
-Firefox
-
+```
+
+{{ LiveSampleLink('Full_IndexedDB_example', "線上範例") }}
+
+## 下一步
+
+請參考[IndexedDB 文件](/zh-TW/docs/IndexedDB),看看有甚麼 IndexedDB API 可供使用,實際試玩一下吧。
+
+## 延伸閱讀
+
+參照
+
+- [IndexedDB API Reference](/en/IndexedDB)
+- [Indexed Database API Specification](http://www.w3.org/TR/IndexedDB/)
+- [Using IndexedDB in chrome](/zh-TW/docs/IndexedDB/Using_IndexedDB_in_chrome)
+
+相關教學
+
+- [A simple TODO list using HTML5 IndexedDB](http://www.html5rocks.com/tutorials/indexeddb/todo/).
+
+ > **備註:** 請注意此教學範例用到的已經廢棄的`setVersion()`方法。
+
+- [Databinding UI Elements with IndexedDB](http://www.html5rocks.com/en/tutorials/indexeddb/uidatabinding/)
+
+相關文章
+
+- [IndexedDB — The Store in Your Browser](http://msdn.microsoft.com/en-us/scriptjunkie/gg679063.aspx)
+
+Firefox
+
+- Mozilla [interface files](https://mxr.mozilla.org/mozilla-central/find?text=&string=dom%2FindexedDB%2F.*%5C.idl®exp=1)
diff --git a/files/zh-tw/web/api/keyboardevent/index.md b/files/zh-tw/web/api/keyboardevent/index.md
index 176fd66c28a075..62e0a9dc2cb5ae 100644
--- a/files/zh-tw/web/api/keyboardevent/index.md
+++ b/files/zh-tw/web/api/keyboardevent/index.md
@@ -5,146 +5,146 @@ tags:
- 待翻譯
translation_of: Web/API/KeyboardEvent
---
-{{APIRef("DOM Events")}}
-
-KeyboardEvent
objects 用來詳述使用者和網頁之間,經由鍵盤產生的互動。每個事件(event
)都記錄著一次鍵盤動作。事件類型(keydown
、 keypress
和 keyup
)用來表示鍵盤執行哪種動作。
-
-注意: KeyboardEvent
僅顯示在鍵盤上發生的事。當你需要進行文字輸入的操作,請使用 HTML5
input
event 代替
KeyboardEvent
。舉例來說,當使用者在手寫系統,例如平板電腦,輸入文字時,並不會啟動 key events 。
-
-Constructor
-
-
- {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
- 建立一 KeyboardEvent
object。
-
-
-Methods
-
-本介面( interface)亦繼承其父, {{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 methods
-
-
- {{domxref("KeyboardEvent.getModifierState()")}}
- 回傳一 {{jsxref("Boolean")}}。用來表示當事件建立時,修飾鍵(例如 Alt 、 Shift 、 Ctrl 、或是 Meta ) 是否是按下的。
- {{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
- 初始化一個 KeyboardEvent
object。這個 method 只有 Gecko 有在使用(其他瀏覽器是使用 {{domxref("KeyboardEvent.initKeyboardEvent()")}}),並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
- {{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
- 初始化一個 KeyboardEvent
object。 Gecko 從未實作過該 method (Gecko 是使用 {{domxref("KeyboardEvent.initKeyEvent()")}}) ,並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
-
-
-Properties
-
-本介面( interface)亦繼承其父,{{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 properties 。
-
-
- {{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
- 一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Alt (OS X 中是 Option 或 ⌥ ) 鍵是否執行中。
- {{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
- 一個 {{domxref("DOMString")}} ,返回鍵盤對應的字符。若是該鍵對應一個實際的字符,則其值為對應該字符的一個非空的 Unicode 字串;若沒對應的話,則返回一個空字串。
- Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
-
- 警告: 在 DOM Level 3 Events ,該 propertie 已被移除。現在只有 IE9+ 支持它。
-
- {{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
- Returns a {{jsxref("Number")}} representing the Unicode reference number of the key; this attribute is used only by the keypress
event. For keys whose char
attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters.
- 警告: 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}} 。
-
- {{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
- 一個 {{domxref("DOMString")}} 。返回事件對應的按鍵的代碼。
- {{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
- 一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Ctrl 鍵是否執行中。
- {{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
- 一個 {{jsxref("Boolean")}} 。用來表示其觸發時間是否在 compositionstart
和 compositionend
之間。
- {{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
- 一個 {{domxref("DOMString")}} ,用來事件對應的按鍵的值(key value)。
- {{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}
- Returns a {{jsxref("Number")}} representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.
- 警告: 此 attribute 已被淘汰。如果可以,建議使用{{domxref("KeyboardEvent.key")}} 。
-
- {{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
- Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.
- Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
-
- {{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
- Returns a {{jsxref("Number")}} representing the location of the key on the keyboard or other input device.
- {{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
- Returns a {{jsxref("Boolean")}} that is true
if the Meta (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞ )) key was active when the key event was generated.
- {{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
- Returns a {{jsxref("Boolean")}} that is true
if the key is being held down such that it is automatically repeating.
- {{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
- Returns a {{jsxref("Boolean")}} that is true
if the Shift key was active when the key event was generated.
- {{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
- Returns a {{jsxref("Number")}} representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode
.
- 警告: 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}} 。
-
-
-
-注意
-
-KeyboardEvent 有 keydown
、 keypress
、 keyup
三種事件。對大多數的按鍵而言, Gecko 觸發事件的順序如下:
-
-
- 當按鍵按下時,會送出 keydown
event 。
- 當按鍵不是特殊鍵( modifier key),例如Ctrl 、Alt ……等等,會送出 keypress
event 。
- 當按鍵放開時,會送出 keyup
event 。
-
-
-特殊狀況
-
-某些按鍵,例如 Caps Lock 、 Num Lock 和 Scroll Lock 能切換鍵盤上的 LED 燈。在 Windows 和 Linux 系統上,這些按鍵只會觸發 keydown
和 keyup
事件。但是 Linux 上的 Firefox 12 或更早的版本亦會觸發 keypress
事件。
-
-而在 Mac 電腦則不同, Caps Lock 只會觸發 keydown
事件;而 Num Lock 則是只有舊版的 Mac 電腦(2007 或之前的版本)才有,現在的 Mac 即便使用外部鍵盤也不支援 Num Lock 。雖說舊版的 Mac 電腦支援 Num Lock 鍵,但 Num Lock 並不會執行任何 KeyboardEvent;而 Gecko 瀏覽器在特殊情況(外接一個有 F14 的鍵盤)下能支援 Scroll Lock ,但是它會產生 keypress
事件。這個異常狀態是個 bug ,詳情可參考 {{bug(602812)}}。
-
-自動迴圈(Auto-Repeat )的執行
-
-當按鍵按下去不放時,它會開始一個自動迴圈。並導致觸發一系列的相似事件,如下所示:
-
-
- keydown
- keypress
- keydown
- keypress
- (不斷重複,直到使用者放開按鍵)
- keyup
-
-
-在 DOM Level 3 說明書有提及這問題是會發生的。其中所存在的問題如下說明:
-
-部分 GTK 環境,例如 Ubuntu 9.4 ,的自動迴圈
-
-部分的 GTK-based 環境之中,自動迴圈在發生的過程中會自動觸發電腦本機的 key-up 事件。然而,對 Gecko 而言,並沒有方法可以分辨使用者重複點擊按鍵與自動迴圈(按鍵按住不放)的差異。在這類的環境下,按鍵按住不放會重複執行下列事件:
-
-
- keydown
- keypress
- keyup
- keydown
- keypress
- keyup
- (不斷重複,直到使用者放開按鍵)
- keyup
-
-
-不幸地,在這些環境之下,web content 亦沒有方法告訴使用者重複點擊按鍵與自動迴圈的差異。
-
-Gecko 5.0 以前的自動迴圈
-
-Gecko 5.0 {{geckoRelease('5.0')}} 以前,在不同平台上,鍵盤的處理與現在相比較不統一。
-
-
- Windows
- 自動迴圈的結果與 Gecko 4.0 或更新的版本類似
- Mac
- 在第一個 keydown 執行後,僅執行 keypress 事件,一直到案件放開(即送出 keyup 事件指令),過程中不會送出任何 keydown 事件。
- Linux
- 鍵盤事件的執行根據平台不同而有所不同。它有可能表現得像是 Windows 也有可能像 Mac ,這取決於本地的事件模型(native event model)是如何執行的。
-
-
-範例
-
-<!DOCTYPE html>
-<html>
-<head>
-<script>
+{{APIRef("DOM Events")}}
+
+**`KeyboardEvent`** objects 用來詳述使用者和網頁之間,經由鍵盤產生的互動。每個事件(`event`)都記錄著一次鍵盤動作。事件類型(`keydown` 、 `keypress` 和 `keyup`)用來表示鍵盤執行哪種動作。
+
+> **備註:** `KeyboardEvent` 僅顯示在鍵盤上發生的事。當你需要進行文字輸入的操作,請使用 HTML5 [`input`](/en-US/docs/DOM/DOM_event_reference/input) event 代替 `KeyboardEvent` 。舉例來說,當使用者在手寫系統,例如平板電腦,輸入文字時,並不會啟動 key events 。
+
+## Constructor
+
+- {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+ - : 建立一 `KeyboardEvent` object。
+
+## Methods
+
+_本介面( interface)亦繼承其父, {{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 methods_
+
+- {{domxref("KeyboardEvent.getModifierState()")}}
+ - : 回傳一 {{jsxref("Boolean")}}。用來表示當事件建立時,修飾鍵(例如 Alt 、 Shift 、 Ctrl 、或是 Meta ) 是否是按下的。
+- {{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+ - : 初始化一個 `KeyboardEvent` object。這個 method 只有 Gecko 有在使用(其他瀏覽器是使用 {{domxref("KeyboardEvent.initKeyboardEvent()")}}),並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
+- {{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+ - : 初始化一個 `KeyboardEvent` object。 Gecko 從未實作過該 method (Gecko 是使用 {{domxref("KeyboardEvent.initKeyEvent()")}}) ,並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
+
+## Properties
+
+_本介面( interface)亦繼承其父,{{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 properties 。_
+
+- {{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+ - : 一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Alt (OS X 中是 Option 或 ⌥ ) 鍵是否執行中。
+- {{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+ - : 一個 {{domxref("DOMString")}} ,返回鍵盤對應的字符。若是該鍵對應一個實際的字符,則其值為對應該字符的一個非空的 Unicode 字串;若沒對應的話,則返回一個空字串。
+
+ > **備註:** If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
+
+ > **警告:** 在 DOM Level 3 Events ,該 propertie 已被移除。現在只有 IE9+ 支持它。
+
+- {{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
+ - : Returns a {{jsxref("Number")}} representing the Unicode reference number of the key; this attribute is used only by the `keypress` event. For keys whose `char` attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters.
+
+ > **警告:** 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}}。
+
+- {{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+ - : 一個 {{domxref("DOMString")}} 。返回事件對應的按鍵的代碼。
+- {{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+ - : 一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Ctrl 鍵是否執行中。
+- {{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+ - : 一個 {{jsxref("Boolean")}} 。用來表示其觸發時間是否在 `compositionstart` 和 `compositionend` 之間。
+- {{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+ - : 一個 {{domxref("DOMString")}} ,用來事件對應的按鍵的值(key value)。
+- {{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}
+ - : Returns a {{jsxref("Number")}} representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.
+
+ > **警告:** 此 attribute 已被淘汰。如果可以,建議使用{{domxref("KeyboardEvent.key")}}。
+
+- {{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
+ - : Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.
+
+ > **備註:** This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
+
+- {{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
+ - : Returns a {{jsxref("Number")}} representing the location of the key on the keyboard or other input device.
+- {{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+ - : Returns a {{jsxref("Boolean")}} that is `true` if the Meta (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞ )) key was active when the key event was generated.
+- {{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
+ - : Returns a {{jsxref("Boolean")}} that is `true` if the key is being held down such that it is automatically repeating.
+- {{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
+ - : Returns a {{jsxref("Boolean")}} that is `true` if the Shift key was active when the key event was generated.
+- {{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
+ - : Returns a {{jsxref("Number")}} representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as `keyCode`.
+
+ > **警告:** 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}} 。
+
+## 注意
+
+KeyboardEvent 有 `keydown` 、 `keypress` 、 `keyup` 三種事件。對大多數的按鍵而言, Gecko 觸發事件的順序如下:
+
+1. 當按鍵按下時,會送出 `keydown` event 。
+2. 當按鍵不是特殊鍵( modifier key),例如
+
+ Ctrl
+
+ 、
+
+ Alt
+
+ ……等等,會送出 `keypress` event 。
+
+3. 當按鍵放開時,會送出 `keyup` event 。
+
+### 特殊狀況
+
+某些按鍵,例如 Caps Lock 、 Num Lock 和 Scroll Lock 能切換鍵盤上的 LED 燈。在 Windows 和 Linux 系統上,這些按鍵只會觸發 `keydown` 和 `keyup` 事件。但是 Linux 上的 Firefox 12 或更早的版本亦會觸發 `keypress` 事件。
+
+而在 Mac 電腦則不同, Caps Lock 只會觸發 `keydown` 事件;而 Num Lock 則是只有舊版的 Mac 電腦(2007 或之前的版本)才有,現在的 Mac 即便使用外部鍵盤也不支援 Num Lock 。雖說舊版的 Mac 電腦支援 Num Lock 鍵,但 Num Lock 並不會執行任何 KeyboardEvent;而 Gecko 瀏覽器在特殊情況(外接一個有 F14 的鍵盤)下能支援 Scroll Lock ,但是它會產生 `keypress` 事件。這個異常狀態是個 bug ,詳情可參考 {{bug(602812)}}。
+
+### 自動迴圈(Auto-Repeat )的執行
+
+當按鍵按下去不放時,它會開始一個自動迴圈。並導致觸發一系列的相似事件,如下所示:
+
+1. `keydown`
+2. `keypress`
+3. `keydown`
+4. `keypress`
+5. (不斷重複,直到使用者放開按鍵)
+6. `keyup`
+
+在 DOM Level 3 說明書有提及這問題是會發生的。其中所存在的問題如下說明:
+
+#### 部分 GTK 環境,例如 Ubuntu 9.4 ,的自動迴圈
+
+部分的 GTK-based 環境之中,自動迴圈在發生的過程中會自動觸發電腦本機的 key-up 事件。然而,對 Gecko 而言,並沒有方法可以分辨使用者重複點擊按鍵與自動迴圈(按鍵按住不放)的差異。在這類的環境下,按鍵按住不放會重複執行下列事件:
+
+1. `keydown`
+2. `keypress`
+3. `keyup`
+4. `keydown`
+5. `keypress`
+6. `keyup`
+7. (不斷重複,直到使用者放開按鍵)
+8. `keyup`
+
+不幸地,在這些環境之下,web content 亦沒有方法告訴使用者重複點擊按鍵與自動迴圈的差異。
+
+#### Gecko 5.0 以前的自動迴圈
+
+Gecko 5.0 {{geckoRelease('5.0')}} 以前,在不同平台上,鍵盤的處理與現在相比較不統一。
+
+- Windows
+ - : 自動迴圈的結果與 Gecko 4.0 或更新的版本類似
+- Mac
+ - : 在第一個 keydown 執行後,僅執行 keypress 事件,一直到案件放開(即送出 keyup 事件指令),過程中不會送出任何 keydown 事件。
+- Linux
+ - : 鍵盤事件的執行根據平台不同而有所不同。它有可能表現得像是 Windows 也有可能像 Mac ,這取決於本地的事件模型(native event model)是如何執行的。
+
+## 範例
+
+```js
+
+
+
+
+
-<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
-</body>
-</html>
-
+
+
+
+```
-規格
+## 規格
{{Specifications}}
-The KeyboardEvent
interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+The `KeyboardEvent` interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
-瀏覽器支援度
+## 瀏覽器支援度
-More compatibility data is available on other pages:
+More compatibility data is available on other pages:
-
- .code
:請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.code")}} 部分。
- .key
:請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.key")}} 部分。
- .getModifierState()
:請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.getModifierState")}} 部分。
-
+- `.code` :請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.code")}} 部分。
+- `.key`:請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.key")}} 部分。
+- `.getModifierState()` :請參考《瀏覽器支援度》的 {{domxref("KeyboardEvent.getModifierState")}} 部分。
{{Compat("api.KeyboardEvent")}}
diff --git a/files/zh-tw/web/api/keyboardevent/keyboardevent/index.md b/files/zh-tw/web/api/keyboardevent/keyboardevent/index.md
index 12d6093e990fa6..08b1b6e80a7c97 100644
--- a/files/zh-tw/web/api/keyboardevent/keyboardevent/index.md
+++ b/files/zh-tw/web/api/keyboardevent/keyboardevent/index.md
@@ -3,135 +3,58 @@ title: KeyboardEvent()
slug: Web/API/KeyboardEvent/KeyboardEvent
translation_of: Web/API/KeyboardEvent/KeyboardEvent
---
-{{APIRef("DOM Events")}}
-
-KeyboardEvent()
constructor 能用來建立一個新的 {{domxref("KeyboardEvent")}}。
-
-語法
-
- event = new KeyboardEvent(typeArg , KeyboardEventInit );
-
-參數
-
-
- typeArg
- 一 {{domxref("DOMString")}} 用來表示事件名稱。
- KeyboardEventInit {{optional_inline}}
- 一個 KeyboardEventInit
dictionary,能接受以下參數:
-
-
-
- 參數
- 可選
- 默認值
- 類型
- 說明
-
-
-
-
- "key"
- ●
- ""
- {{domxref("DOMString")}}
- 用來設定 {{domxref("KeyboardEvent.key")}} 的值
-
-
- "code"
- ●
- ""
- {{domxref("DOMString")}}
- 用來設定 {{domxref("KeyboardEvent.code")}} 的值
-
-
- "location"
- ●
- 0
- unsigned long
- 用來設定 {{domxref("KeyboardEvent.location")}} 的值
-
-
- "ctrlKey"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.ctrlKey")}} 的值
-
-
- "shiftKey"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.shiftKey")}} 的值
-
-
- "altKey"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.altKey")}} 的值
-
-
- "metaKey"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.metaKey")}} 的值
-
-
- "repeat"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.repeat")}} 的值
-
-
- "isComposing"
- ●
- false
- {{jsxref("Boolean")}}
- 用來設定 {{domxref("KeyboardEvent.isComposing")}} 的值
-
-
- "charCode"
- ●
- 0
- unsigned long
- 用來設定 {{domxref("KeyboardEvent.charCode")}} 的值
-
-
- "keyCode"
- ●
- 0
- unsigned long
- 用來設定 {{domxref("KeyboardEvent.keyCode")}} 的值
-
-
- "which"
- ●
- 0
- unsigned long
- 用來設定 {{domxref("KeyboardEvent.which")}} 的值
-
-
-
-
-
-
KeyboardEventInit
dictionary 亦接受 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 和{{domxref("Event.Event", "EventInit")}} 所接受的參數。
-
-
-
-
-規格
+{{APIRef("DOM Events")}}
+
+**`KeyboardEvent()`** constructor 能用來建立一個新的 {{domxref("KeyboardEvent")}}。
+
+## 語法
+
+```plain
+ event = new KeyboardEvent(typeArg, KeyboardEventInit);
+```
+
+### 參數
+
+- `type`
+ - : 一 {{domxref("DOMString")}} 用來表示事件名稱。
+- `options` {{optional_inline}}
+ - : 一個 `KeyboardEventInit` dictionary,能接受以下參數:
+
+ - `key` {{optional_inline}}
+ - : 一個字符串,默認值為 `""`,用來設定 {{domxref("KeyboardEvent.key")}} 的值。
+ - `code` {{optional_inline}}
+ - : 一個字符串,默認值為 `""`,用來設定 {{domxref("KeyboardEvent.code")}} 的值。
+ - `location` {{optional_inline}}
+ - : 一個 `unsigned long`,默認值為 `0`,用來設定 {{domxref("KeyboardEvent.location")}} 的值。
+ - `ctrlKey` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.ctrlKey")}} 的值。
+ - `shiftKey` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.shiftKey")}} 的值。
+ - `altKey` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.altKey")}} 的值。
+ - `metaKey` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.metaKey")}} 的值。
+ - `repeat` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.repeat")}} 的值。
+ - `isComposing` {{optional_inline}}
+ - : 一個 {{jsxref("Boolean")}},默認值為 `false`,用來設定 {{domxref("KeyboardEvent.isComposing")}} 的值。
+ - `charCode` {{optional_inline}}
+ - : 一個 `unsigned long`,默認值為 `0`,用來設定 {{domxref("KeyboardEvent.charCode")}} 的值。
+ - `keyCode` {{optional_inline}}
+ - : 一個 `unsigned long`,默認值為 `0`,用來設定 {{domxref("KeyboardEvent.keyCode")}} 的值。
+ - `which` {{optional_inline}}
+ - : 一個 `unsigned long`,默認值為 `0`,用來設定 {{domxref("KeyboardEvent.which")}} 的值
+
+> **備註:** _`KeyboardEventInit` dictionary 亦接受 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 和{{domxref("Event.Event", "EventInit")}} 所接受的參數。_
+
+## 規格
{{Specifications}}
-瀏覽器支援度
+## 瀏覽器支援度
{{Compat("api.KeyboardEvent.KeyboardEvent")}}
-延伸閱讀
+## 延伸閱讀
-
- {{domxref("KeyboardEvent")}} ,此 constructer 所建立的 object 的 interface
-
+- {{domxref("KeyboardEvent")}} ,此 constructer 所建立的 object 的 interface
diff --git a/files/zh-tw/web/api/media_capture_and_streams_api/index.md b/files/zh-tw/web/api/media_capture_and_streams_api/index.md
index 8c0b9710959e82..eedab4811aabd7 100644
--- a/files/zh-tw/web/api/media_capture_and_streams_api/index.md
+++ b/files/zh-tw/web/api/media_capture_and_streams_api/index.md
@@ -9,78 +9,68 @@ tags:
translation_of: Web/API/Media_Streams_API
original_slug: Web/API/Media_Streams_API
---
-{{DefaultAPISidebar("Media Capture and Streams")}}
+{{DefaultAPISidebar("Media Capture and Streams")}}
-該媒體捕獲和流 API,通常被稱為媒體流API 或者乾脆MediaStream API ,是關係到一個API的WebRTC 提供流式音頻和視頻數據的支持。它提供了用於處理流及其組成軌道的接口和方法,與數據格式關聯的約束,異步使用數據時的成功和錯誤回調以及在此過程中觸發的事件。
+該**媒體捕獲和流**API,通常被稱為**媒體流 API**或者乾脆**MediaStream API**,是關係到一個 API[的 WebRTC](/zh-TW/docs/Web/API/WebRTC_API)提供流式音頻和視頻數據的支持。它提供了用於處理流及其組成軌道的接口和方法,與數據格式關聯的約束,異步使用數據時的成功和錯誤回調以及在此過程中觸發的事件。
-概念和用法
+## 概念和用法
-該API基於{{domxref("MediaStream")}}對象的操作,該對象代表與音頻或視頻相關的數據流。請參閱“獲取視頻”中 的示例。
+該 API 基於{{domxref("MediaStream")}}對象的操作,該對象代表與音頻或視頻相關的數據流。請參閱“[獲取視頻”中](/zh-TW/docs/WebRTC/taking_webcam_photos#Get_the_video)的示例。
-A MediaStream
consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks . Each MediaStreamTrack
may have one or more channels . The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.
+A `MediaStream` consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video **tracks**. Each `MediaStreamTrack` may have one or more **channels**. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like _left_ or _right_ in a stereo audio track.
-MediaStream
objects have a single input and a single output . A MediaStream
object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local , and has as its source input one of the user's cameras or microphones. A non-local MediaStream
may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.
+`MediaStream` objects have a single **input** and a single **output**. A `MediaStream` object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called _local_, and has as its source input one of the user's cameras or microphones. A non-local `MediaStream` may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the [Web Audio API](/zh-TW/docs/Web/API/Web_Audio_API) {{domxref("MediaStreamAudioSourceNode")}}.
-The output of the MediaStream
object is linked to a consumer . It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}}, the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.
+The output of the `MediaStream` object is linked to a **consumer**. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}}, the WebRTC {{domxref("RTCPeerConnection")}} API or a [Web Audio API](/zh-TW/docs/Web/API/Web_Audio_API) {{domxref("MediaStreamAudioSourceNode")}}.
-Interfaces
+## Interfaces
-In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API.
+In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API.
-
-
- {{domxref("BlobEvent")}}
- {{domxref("CanvasCaptureMediaStreamTrack")}}
- {{domxref("InputDeviceInfo")}}
- {{domxref("MediaDeviceKind")}}
- {{domxref("MediaDeviceInfo")}}
- {{domxref("MediaDevices")}}
- {{domxref("MediaStream")}}
- {{domxref("MediaStreamConstraints")}}
- {{domxref("MediaStreamEvent")}}
- {{domxref("MediaStreamTrack")}}
- {{domxref("MediaStreamTrackEvent")}}
- {{domxref("MediaTrackCapabilities")}}
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaTrackSettings")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("NavigatorUserMedia")}}
- {{domxref("NavigatorUserMediaError")}}
- {{domxref("OverconstrainedError")}}
- {{domxref("URL")}}
-
-
+- {{domxref("BlobEvent")}}
+- {{domxref("CanvasCaptureMediaStreamTrack")}}
+- {{domxref("InputDeviceInfo")}}
+- {{domxref("MediaDeviceKind")}}
+- {{domxref("MediaDeviceInfo")}}
+- {{domxref("MediaDevices")}}
+- {{domxref("MediaStream")}}
+- {{domxref("MediaStreamConstraints")}}
+- {{domxref("MediaStreamEvent")}}
+- {{domxref("MediaStreamTrack")}}
+- {{domxref("MediaStreamTrackEvent")}}
+- {{domxref("MediaTrackCapabilities")}}
+- {{domxref("MediaTrackConstraints")}}
+- {{domxref("MediaTrackSettings")}}
+- {{domxref("MediaTrackSupportedConstraints")}}
+- {{domxref("NavigatorUserMedia")}}
+- {{domxref("NavigatorUserMediaError")}}
+- {{domxref("OverconstrainedError")}}
+- {{domxref("URL")}}
-Early versions of the Media Capture and Streams API specification included separate AudioStreamTrack
and VideoStreamTrack
interfaces—each based upon {{domxref("MediaStreamTrack")}}—which represented streams of those types. These no longer exist, and you should update any existing code to instead use MediaStreamTrack
directly.
+Early versions of the Media Capture and Streams API specification included separate `AudioStreamTrack` and `VideoStreamTrack` interfaces—each based upon {{domxref("MediaStreamTrack")}}—which represented streams of those types. These no longer exist, and you should update any existing code to instead use `MediaStreamTrack` directly.
-Events
+## Events
-
-
- {{event("addtrack")}}
- {{event("ended")}}
- {{event("muted")}}
- {{event("overconstrained")}}
- {{event("removetrack")}}
- {{event("started")}}
- {{event("unmuted")}}
-
-
+- {{event("addtrack")}}
+- {{event("ended")}}
+- {{event("muted")}}
+- {{event("overconstrained")}}
+- {{event("removetrack")}}
+- {{event("started")}}
+- {{event("unmuted")}}
-Guides and tutorials
+## Guides and tutorials
-The articles below provide additional guidance and how-to information that will help you learn to use the API, and how to perform specific tasks that you may wish to handle.
+The articles below provide additional guidance and how-to information that will help you learn to use the API, and how to perform specific tasks that you may wish to handle.
-{{LandingPageListSubpages}}
+{{LandingPageListSubpages}}
-Browser compatibility
+## Browser compatibility
-{{Compat("api.MediaStream")}}
+{{Compat("api.MediaStream")}}
-也可以看看
+## 也可以看看
-
- WebRTC -API簡介頁
- {{domxref("mediaDevices.getUserMedia()")}}
- 使用WebRTC拍攝靜態照片 :有關使用getUserMedia()
。
-
+- [WebRTC](/zh-TW/docs/Web/API/WebRTC_API) -API 簡介頁
+- {{domxref("mediaDevices.getUserMedia()")}}
+- [使用 WebRTC 拍攝靜態照片](/zh-TW/docs/Web/API/WebRTC_API/Taking_still_photos):有關使用`getUserMedia()`。
diff --git a/files/zh-tw/web/api/mediaquerylist/index.md b/files/zh-tw/web/api/mediaquerylist/index.md
index d119a78646a289..1de490c9a78201 100644
--- a/files/zh-tw/web/api/mediaquerylist/index.md
+++ b/files/zh-tw/web/api/mediaquerylist/index.md
@@ -3,96 +3,70 @@ title: MediaQueryList
slug: Web/API/MediaQueryList
translation_of: Web/API/MediaQueryList
---
-{{APIRef("CSSOM View")}}{{SeeCompatTable}}
-
-MediaQueryList
物件維護一組針對 {{ domxref("document") }} 的 media querie , 並且當 media querie 相對應的文件狀態改變時,觸發註冊的事件處理器通知之。
-
-MediaQueryList 物件讓我們不用一直定期去偵測,而是直接去觀察文件的狀態變化。
-
-Method overview
-
-
-
-Properties
-
-
-
-
-
-
-
-
-
- matches
- boolean
- true
當 {{ domxref("document") }} 目前狀態符合 media query list 所維護的條件; 否則 false。 唯獨。
-
-
- media
- DOMString
- 序列化 (serialized) 的 media query list.
-
-
-
-
-Methods
-
-addListener()
-
-添加一個新的事件處理器 (listener),若 listener 已存在則無作用。
-
-void addListener(
+{{APIRef("CSSOM View")}}{{SeeCompatTable}}
+
+`MediaQueryList` 物件維護一組針對 {{ domxref("document") }} 的 [media querie](/zh-TW/docs/CSS/Media_queries) , 並且當 media querie 相對應的文件狀態改變時,觸發註冊的事件處理器通知之。
+
+MediaQueryList 物件讓我們不用一直定期去偵測,而是直接去觀察文件的狀態變化。
+
+## Method overview
+
+| `void addListener(MediaQueryListListener listener);` |
+| ------------------------------------------------------- |
+| `void removeListener(MediaQueryListListener listener);` |
+
+## Properties
+
+| Property | Type | Description |
+| --------- | ----------- | -------------------------------------------------------------------------------------------------------------- |
+| `matches` | `boolean` | `true` 當 {{ domxref("document") }} 目前狀態符合 media query list 所維護的條件; 否則 false。 唯獨**。** |
+| `media` | `DOMString` | 序列化 (serialized) 的 media query list. |
+
+## Methods
+
+### addListener()
+
+添加一個新的事件處理器 (listener),若 listener 已存在則無作用。
+
+```plain
+void addListener(
MediaQueryListListener listener
-);
+);
+```
-Parameter (for addListener method)
+#### Parameter (for addListener method)
-
- listener
- 當 media query 對應的狀態改變時所觸發的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
-
+- `listener`
+ - : 當 media query 對應的狀態改變時所觸發的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
-removeListener()
+### removeListener()
-移除一個事件處理器 (listener),若 listener 不存在則無作用。
+移除一個事件處理器 (listener),若 listener 不存在則無作用。
-void removeListener(
+```plain
+void removeListener(
MediaQueryListListener listener
-);
+);
+```
-Parameter (for removeListener method)
+#### Parameter (for removeListener method)
-
- listener
- 欲移除的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
-
+- `listener`
+ - : 欲移除的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.MediaQueryList")}}
-
+##
-規範標準
+## 規範標準
-
+- [The CSSOM View Module: The MediaQueryList Interface](http://dev.w3.org/csswg/cssom-view/#the-mediaquerylist-interface)
-延伸閱讀
+## 延伸閱讀
-
+- [Media queries](/zh-TW/docs/CSS/Media_queries)
+- [Using media queries from code](/zh-TW/docs/CSS/Using_media_queries_from_code)
+- {{ domxref("window.matchMedia()") }}
+- {{ domxref("MediaQueryListListener") }}
diff --git a/files/zh-tw/web/api/mediasource/index.md b/files/zh-tw/web/api/mediasource/index.md
index fd80ebd9aa00d1..c588bb58fe1875 100644
--- a/files/zh-tw/web/api/mediasource/index.md
+++ b/files/zh-tw/web/api/mediasource/index.md
@@ -3,85 +3,71 @@ title: MediaSource
slug: Web/API/MediaSource
translation_of: Web/API/MediaSource
---
-{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
-Media Source Extensions API 的 MediaSource
介面代表 {{domxref("HTMLMediaElement")}} 物件的媒體資料來源。一個 MediaSource
物件可以被附加到一個 {{domxref("HTMLMediaElement")}} 以被用戶代理 (user agent) 播放。
+[Media Source Extensions API](/zh-TW/docs/Web/API/Media_Source_Extensions_API) 的 **`MediaSource`** 介面代表 {{domxref("HTMLMediaElement")}} 物件的媒體資料來源。一個 `MediaSource` 物件可以被附加到一個 {{domxref("HTMLMediaElement")}} 以被用戶代理 (user agent) 播放。
-{{InheritanceDiagram}}
+{{InheritanceDiagram}}
-建構子 (Constructor)
+## 建構子 (Constructor)
-
- {{domxref("MediaSource.MediaSource", "MediaSource()")}}
- 建構且回傳一個新的 MediaSource
物件但不與任何來源緩衝 (source buffers) 關聯 (associate)。
-
+- {{domxref("MediaSource.MediaSource", "MediaSource()")}}
+ - : 建構且回傳一個新的 `MediaSource` 物件但不與任何來源緩衝 (source buffers) 關聯 (associate)。
-屬性 (Properties)
+## 屬性 (Properties)
-
- {{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
- 回傳一個含有與此 MediaSource
關聯的 {{domxref("SourceBuffer")}} 物件串列的 {{domxref("SourceBufferList")}} 物件。
- {{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
- 回傳一個 {{domxref("SourceBufferList")}} 物件,含有 {{domxref("SourceBuffers")}} 的子集合 {{domxref("SourceBuffer")}} 物件 — 物件的串列提供被選擇的影片軌 (video track), 啟用的音軌 (audio tracks), 以及顯示或隱藏的字軌。
- {{domxref("MediaSource.readyState")}} {{readonlyInline}}
- 回傳一個列舉類型表示目前 MediaSource
的狀態:沒有附加到媒體元件 (closed
),已經附加且可以接收 {{domxref("SourceBuffer")}} 物件 (open
),已經附加但是串流已經經由 {{domxref("MediaSource.endOfStream()")}} 結束 (ended
)。
- {{domxref("MediaSource.duration")}}
- 取得或設置現在正被表示的媒體的時間長度。
-
- 事件處理函數 (Event handlers)
+- {{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
+ - : 回傳一個含有與此 `MediaSource` 關聯的 {{domxref("SourceBuffer")}} 物件串列的 {{domxref("SourceBufferList")}} 物件。
+- {{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
+ - : 回傳一個 {{domxref("SourceBufferList")}} 物件,含有 {{domxref("SourceBuffers")}} 的子集合 {{domxref("SourceBuffer")}} 物件 — 物件的串列提供被選擇的影片軌 (video track), 啟用的音軌 (audio tracks), 以及顯示或隱藏的字軌。
+- {{domxref("MediaSource.readyState")}} {{readonlyInline}}
+ - : 回傳一個列舉類型表示目前 `MediaSource` 的狀態:沒有附加到媒體元件 (`closed`),已經附加且可以接收 {{domxref("SourceBuffer")}} 物件 (`open`),已經附加但是串流已經經由 {{domxref("MediaSource.endOfStream()")}} 結束 (`ended`)。
+- {{domxref("MediaSource.duration")}}
+ - : 取得或設置現在正被表示的媒體的時間長度。
+- ### 事件處理函數 (Event handlers)
+ {{domxref("MediaSource.onsourceclose")}}
-
- {{domxref("MediaSource.onsourceclose")}}
- sourceclose
事件的事件處理函數。
- {{domxref("MediaSource.onsourceended")}}
- sourceended
事件的事件處理函數。
- {{domxref("MediaSource.onsourceopen")}}
- sourceopen
事件的事件處理函數。
-
+ - : `sourceclose` 事件的事件處理函數。
-
-
+- {{domxref("MediaSource.onsourceended")}}
+ - : `sourceended` 事件的事件處理函數。
+- {{domxref("MediaSource.onsourceopen")}}
+ - : `sourceopen` 事件的事件處理函數。
-
-
+## 方法 (Methods)
-方法 (Methods)
+_從親介面 (parent interface) {{domxref("EventTarget")}} 繼承屬性。_
-從親介面 (parent interface) {{domxref("EventTarget")}} 繼承屬性。
+- {{domxref("MediaSource.addSourceBuffer()")}}
+ - : 依據指定的 MIME 類型建立一個新的 {{domxref("SourceBuffer")}} 且將其加入 `MediaSource` 的 {{domxref("SourceBuffers")}} 串列。
+- {{domxref("MediaSource.clearLiveSeekableRange()")}}
+ - : 清除先前藉由呼叫 `setLiveSeekableRange()` 所設定的可尋找範圍。
+- {{domxref("MediaSource.endOfStream()")}}
+ - : 示意串流的結束。
+- {{domxref("MediaSource.removeSourceBuffer()")}}
+ - : 從與此 `MediaSource` 物件關聯的 {{domxref("SourceBuffers")}} 串列移除指定的 {{domxref("SourceBuffer")}}。
+- {{domxref("MediaSource.setLiveSeekableRange()")}}
+ - : 設定使用者可以在媒體元素中的可尋找範圍。
-
- {{domxref("MediaSource.addSourceBuffer()")}}
- 依據指定的 MIME 類型建立一個新的 {{domxref("SourceBuffer")}} 且將其加入 MediaSource
的 {{domxref("SourceBuffers")}} 串列。
- {{domxref("MediaSource.clearLiveSeekableRange()")}}
- 清除先前藉由呼叫 setLiveSeekableRange()
所設定的可尋找範圍。
- {{domxref("MediaSource.endOfStream()")}}
- 示意串流的結束。
- {{domxref("MediaSource.removeSourceBuffer()")}}
- 從與此 MediaSource
物件關聯的 {{domxref("SourceBuffers")}} 串列移除指定的 {{domxref("SourceBuffer")}}。
- {{domxref("MediaSource.setLiveSeekableRange()")}}
- 設定使用者可以在媒體元素中的可尋找範圍。
-
+## 靜態方法 (Static methods)
-靜態方法 (Static methods)
+- {{domxref("MediaSource.isTypeSupported()")}}
+ - : 回傳一個 {{domxref("Boolean")}} 值表示指定的 MIME 類型是否被現在的用戶代理支援 — 意即可否成功的為該 MIME 類型建立 {{domxref("SourceBuffer")}} 物件。
-
- {{domxref("MediaSource.isTypeSupported()")}}
- 回傳一個 {{domxref("Boolean")}} 值表示指定的 MIME 類型是否被現在的用戶代理支援 — 意即可否成功的為該 MIME 類型建立 {{domxref("SourceBuffer")}} 物件。
-
+## 範例
-範例
+以下簡單的範例儘快的載入一個個影片塊 (chunk) 且儘快的播放。這個範例是由 Nick Desaulniers 所撰寫且可以[在此實際觀看](http://nickdesaulniers.github.io/netfix/demo/bufferAll.html)(您也可以[下載原始碼](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferAll.html)以更進一步研究)
-以下簡單的範例儘快的載入一個個影片塊 (chunk) 且儘快的播放。這個範例是由 Nick Desaulniers 所撰寫且可以在此實際觀看 (您也可以下載原始碼 以更進一步研究)
-
-var video = document.querySelector('video');
+```js
+var video = document.querySelector('video');
var assetURL = 'frag_bunny.mp4';
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
-if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
+if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource();
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
@@ -113,19 +99,18 @@ function fetchAB (url, cb) {
cb(xhr.response);
};
xhr.send();
-};
+};
+```
-規格
+## 規格
{{Specifications}}
-相容性表格
+## 相容性表格
-{{Compat("api.MediaSource")}}
+{{Compat("api.MediaSource")}}
-相關資料
+## 相關資料
-
- {{domxref("SourceBuffer")}}
- {{domxref("SourceBufferList")}}
-
+- {{domxref("SourceBuffer")}}
+- {{domxref("SourceBufferList")}}
diff --git a/files/zh-tw/web/api/messageevent/index.md b/files/zh-tw/web/api/messageevent/index.md
index 76d8f39fd4ca5a..16146c86a8c1b5 100644
--- a/files/zh-tw/web/api/messageevent/index.md
+++ b/files/zh-tw/web/api/messageevent/index.md
@@ -6,35 +6,22 @@ tags:
translation_of: Web/API/MessageEvent
original_slug: WebSockets/WebSockets_reference/MessageEvent
---
-當伺服器傳來資料時,客戶端會收到一個 MessageEvent
,由 WebSocket
物件 onmessage
表示的監聽器接收。
-
-屬性
-
-
-
-
-
-
-
-
-
- data
- {{ domxref("DOMString") }} | {{ domxref("Blob") }} | ArrayBuffer
- 伺服器傳來的資料。
-
-
-
-
-規範
+當伺服器傳來資料時,客戶端會收到一個 `MessageEvent`,由 `WebSocket` 物件 `onmessage` 表示的監聽器接收。
+
+## 屬性
+
+| 屬性 | 形態 | 描述 |
+| ------ | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
+| `data` | {{ domxref("DOMString") }} \| {{ domxref("Blob") }} \| [`ArrayBuffer`](/zh_tw/JavaScript_typed_arrays/ArrayBuffer) | 伺服器傳來的資料。 |
+
+## 規範
{{Specifications}}
-瀏覽器兼容
+## 瀏覽器兼容
{{Compat("api.MessageEvent")}}
-參見
+## 參見
-
+- [`WebSocket`](/zh_tw/WebSockets/WebSockets_reference/WebSocket)
diff --git a/files/zh-tw/web/api/mouseevent/index.md b/files/zh-tw/web/api/mouseevent/index.md
index 0a697970d9a308..570334a925dadb 100644
--- a/files/zh-tw/web/api/mouseevent/index.md
+++ b/files/zh-tw/web/api/mouseevent/index.md
@@ -3,114 +3,101 @@ title: MouseEvent
slug: Web/API/MouseEvent
translation_of: Web/API/MouseEvent
---
-{{APIRef("DOM Events")}}
-
-MouseEvent
介面表示了由使用者經指標裝置(如滑鼠)進行互動所發生的事件。常見的 MouseEvent
實作事件包括了 {{event("click")}}、{{event("dblclick")}}、{{event("mouseup")}} 與 {{event("mousedown")}}。
-
-MouseEvent
繼承自 {{domxref("UIEvent")}},而 UIEvent
則繼承自 {{domxref("Event")}}。雖然 {{domxref("MouseEvent.initMouseEvent()")}} 方法仍然向下相容新的瀏覽器,但現今應該使用 {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} 建構式來建立 MouseEvent
物件。
-
-另外還有一些特定的事件繼承自 MouseEvent
:{{domxref("WheelEvent")}} 及 {{domxref("DragEvent")}}。
-
-建構式
-
-
- {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
- 建立一個 MouseEvent
物件。
-
-
-屬性
-
-此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的屬性
-
-
- {{domxref("MouseEvent.altKey")}} {{readonlyinline}}
- Returns true
if the alt key was down when the mouse event was fired.
- {{domxref("MouseEvent.button")}} {{readonlyinline}}
- The button number that was pressed when the mouse event was fired.
- {{domxref("MouseEvent.buttons")}} {{readonlyinline}}
-
- The buttons being pressed when the mouse event was fired
-
- {{domxref("MouseEvent.clientX")}} {{readonlyinline}}
- The X coordinate of the mouse pointer in local (DOM content) coordinates.
- {{domxref("MouseEvent.clientY")}} {{readonlyinline}}
- The Y coordinate of the mouse pointer in local (DOM content) coordinates.
- {{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
- Returns true
if the control key was down when the mouse event was fired.
- {{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
- Returns true
if the meta key was down when the mouse event was fired.
- {{domxref("MouseEvent.movementX")}} {{readonlyinline}}
- The X coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
- {{domxref("MouseEvent.movementY")}} {{readonlyinline}}
- The Y coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
- {{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
- The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
- {{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
- The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
- {{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
- The X coordinate of the mouse pointer relative to the whole document.
- {{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
- The Y coordinate of the mouse pointer relative to the whole document.
- {{domxref("MouseEvent.region")}} {{readonlyinline}}
- Returns the id of the hit region affected by the event. If no hit region is affected, null
is returned.
- {{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
-
- The secondary target for the event, if there is one.
-
- {{domxref("MouseEvent.screenX")}} {{readonlyinline}}
- The X coordinate of the mouse pointer in global (screen) coordinates.
- {{domxref("MouseEvent.screenY")}} {{readonlyinline}}
- The Y coordinate of the mouse pointer in global (screen) coordinates.
- {{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
- Returns true
if the shift key was down when the mouse event was fired.
- {{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
- The button being pressed when the mouse event was fired.
- {{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}
- The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0
(minimum pressure) and 1.0
(maximum pressure).
- {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
-
- The type of device that generated the event (one of the MOZ_SOURCE_*
constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).
-
- {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
- The amount of pressure applied when clicking
- {{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
- Alias for {{domxref("MouseEvent.clientX")}}.
- {{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
- Alias for {{domxref("MouseEvent.clientY")}}
-
-
-Constants
-
-
- {{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
- Minimum force necessary for a normal click
- {{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
- Minimum force necessary for a force click
-
-
-方法
-
-此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的方法
-
-
- {{domxref("MouseEvent.getModifierState()")}}
- Returns the current state of the specified modifier key. See the {{domxref("KeyboardEvent.getModifierState")}}() for details.
- {{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
- Initializes the value of a MouseEvent
created. If the event has already being dispatched, this method does nothing.
-
-
-範例
-
-This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods.
-
-function simulateClick() {
- var evt = new MouseEvent ("click", {
+{{APIRef("DOM Events")}}
+
+**`MouseEvent`** 介面表示了由使用者經指標裝置(如滑鼠)進行互動所發生的事件。常見的 `MouseEvent` 實作事件包括了 {{event("click")}}、{{event("dblclick")}}、{{event("mouseup")}} 與 {{event("mousedown")}}。
+
+`MouseEvent` 繼承自 {{domxref("UIEvent")}},而 `UIEvent` 則繼承自 {{domxref("Event")}}。雖然 {{domxref("MouseEvent.initMouseEvent()")}} 方法仍然向下相容新的瀏覽器,但現今應該使用 {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} 建構式來建立 `MouseEvent` 物件。
+
+另外還有一些特定的事件繼承自 `MouseEvent`:{{domxref("WheelEvent")}} 及 {{domxref("DragEvent")}}。
+
+## 建構式
+
+- {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
+ - : 建立一個 `MouseEvent` 物件。
+
+## 屬性
+
+_此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的屬性_
+
+- {{domxref("MouseEvent.altKey")}} {{readonlyinline}}
+ - : Returns `true` if the alt key was down when the mouse event was fired.
+- {{domxref("MouseEvent.button")}} {{readonlyinline}}
+ - : The button number that was pressed when the mouse event was fired.
+- {{domxref("MouseEvent.buttons")}} {{readonlyinline}}
+ - : The buttons being pressed when the mouse event was fired
+- {{domxref("MouseEvent.clientX")}} {{readonlyinline}}
+ - : The X coordinate of the mouse pointer in local (DOM content) coordinates.
+- {{domxref("MouseEvent.clientY")}} {{readonlyinline}}
+ - : The Y coordinate of the mouse pointer in local (DOM content) coordinates.
+- {{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
+ - : Returns `true` if the control key was down when the mouse event was fired.
+- {{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
+ - : Returns `true` if the meta key was down when the mouse event was fired.
+- {{domxref("MouseEvent.movementX")}} {{readonlyinline}}
+ - : The X coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+- {{domxref("MouseEvent.movementY")}} {{readonlyinline}}
+ - : The Y coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+- {{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
+ - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+- {{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
+ - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+- {{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
+ - : The X coordinate of the mouse pointer relative to the whole document.
+- {{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
+ - : The Y coordinate of the mouse pointer relative to the whole document.
+- {{domxref("MouseEvent.region")}} {{readonlyinline}}
+ - : Returns the id of the hit region affected by the event. If no hit region is affected, `null` is returned.
+- {{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
+ - : The secondary target for the event, if there is one.
+- {{domxref("MouseEvent.screenX")}} {{readonlyinline}}
+ - : The X coordinate of the mouse pointer in global (screen) coordinates.
+- {{domxref("MouseEvent.screenY")}} {{readonlyinline}}
+ - : The Y coordinate of the mouse pointer in global (screen) coordinates.
+- {{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
+ - : Returns `true` if the shift key was down when the mouse event was fired.
+- {{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
+ - : The button being pressed when the mouse event was fired.
+- {{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}
+ - : The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between `0.0` (minimum pressure) and `1.0` (maximum pressure).
+- {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
+ - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).
+- {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+ - : The amount of pressure applied when clicking
+- {{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
+ - : Alias for {{domxref("MouseEvent.clientX")}}.
+- {{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
+ - : Alias for {{domxref("MouseEvent.clientY")}}
+
+## Constants
+
+- {{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+ - : Minimum force necessary for a normal click
+- {{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+ - : Minimum force necessary for a force click
+
+## 方法
+
+_此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的方法_
+
+- {{domxref("MouseEvent.getModifierState()")}}
+ - : Returns the current state of the specified modifier key. See the {{domxref("KeyboardEvent.getModifierState")}}() for details.
+- {{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
+ - : Initializes the value of a `MouseEvent` created. If the event has already being dispatched, this method does nothing.
+
+## 範例
+
+This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods.
+
+```js
+function simulateClick() {
+ var evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
});
var cb = document.getElementById("checkbox"); //element to click on
- var canceled = !cb.dispatchEvent (evt);
+ var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
@@ -119,25 +106,26 @@ translation_of: Web/API/MouseEvent
alert("not canceled");
}
}
-document.getElementById("button").addEventListener('click', simulateClick);
+document.getElementById("button").addEventListener('click', simulateClick);
+```
-<p><label><input type="checkbox" id="checkbox"> Checked</label>
-<p><button id="button">Click me</button>
+```html
+ Checked
+
Click me
+```
-
Click on the button to see how the sample works:
+Click on the button to see how the sample works:
-{{ EmbedLiveSample('Example', '', '', '') }}
+{{ EmbedLiveSample('Example', '', '', '') }}
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.MouseEvent")}}
-參見
+## 參見
-
- Its direct parent, {{domxref("UIEvent")}}.
-
+- Its direct parent, {{domxref("UIEvent")}}.
diff --git a/files/zh-tw/web/api/mutationobserver/index.md b/files/zh-tw/web/api/mutationobserver/index.md
index 9d68dc5a77d57f..ba18486ce285ff 100644
--- a/files/zh-tw/web/api/mutationobserver/index.md
+++ b/files/zh-tw/web/api/mutationobserver/index.md
@@ -3,194 +3,114 @@ title: MutationObserver
slug: Web/API/MutationObserver
translation_of: Web/API/MutationObserver
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-MutationObserver
提供開發人員一個方法,來對 DOM tree 的變動來作反應,這被設計用來替換在 DOM3 事件規範中的 Mutation Events 。
+`MutationObserver` 提供開發人員一個方法,來對 [DOM](/zh-TW/docs/DOM) tree 的變動來作反應,這被設計用來替換在 DOM3 事件規範中的 [Mutation Events](/zh-TW/docs/DOM/Mutation_events)。
-建構式
+## 建構式
-MutationObserver()
+### `MutationObserver()`
-以下舉例為一個新的 DOM mutation observers 建構式。
+以下舉例為一個新的 DOM mutation observers 建構式。
-new MutationObserver(
+```plain
+new MutationObserver(
function callback
);
-
+```
-參數
+#### 參數
-
- callback
- 這個函式會在 DOM 有變化時被呼叫,observer 會用兩個參數來呼叫它,第一個是 MutationRecord
物件陣列,而第二個參數則是觀察者目標本身。
-
+- `callback`
+ - : 這個函式會在 DOM 有變化時被呼叫,observer 會用兩個參數來呼叫它,第一個是 `MutationRecord `物件陣列,而第二個參數則是觀察者目標本身。
-Instance methods
+## Instance methods
-
+| `void observe( {{domxref("Node")}} target, MutationObserverInit options );` |
+| -------------------------------------------------------------------------------- |
+| `void disconnect();` |
+| `Array takeRecords();` |
-
-
筆記 : {{domxref("Node")}} target should not be confused with NodeJS .
-
+> **備註:** {{domxref("Node")}} target should not be confused with [NodeJS](https://nodejs.org/en/).
-observe()
+### `observe()`
-Registers the MutationObserver
instance to receive notifications of DOM mutations on the specified node.
+Registers the `MutationObserver` instance to receive notifications of DOM mutations on the specified node.
-void observe(
+```plain
+void observe(
{{domxref("Node")}} target,
- MutationObserverInit
options
+ MutationObserverInit options
);
-
-
-Parameters
-
-
- target
- The {{domxref("Node")}} on which to observe DOM mutations.
- options
- A MutationObserverInit
object, specifies which DOM mutations should be reported.
-
-
-NOTE: Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it.
-
-disconnect()
-
-Stops the MutationObserver
instance from receiving notifications of DOM mutations. Until the observe()
method is used again, observer's callback will not be invoked.
-
-void disconnect();
-
-
-takeRecords()
-
-Empties the MutationObserver
instance's record queue and returns what was in there.
-
-Array takeRecords();
-
-
-Return value
-
-Returns an Array of MutationRecord
s .
-
-MutationObserverInit
-
-MutationObserverInit
is an object which can specify the following properties:
-
-NOTE: At the very least, childList
, attributes
, or characterData
must be set to true
. Otherwise, "An invalid or illegal string was specified" error is thrown.
-
-
-
-
-
-
-
-
- childList
- Set to true
if additions and removals of the target node's child elements (including text nodes) are to be observed.
-
-
- attributes
- Set to true
if mutations to target's attributes are to be observed.
-
-
- characterData
- Set to true
if mutations to target's data are to be observed.
-
-
- subtree
- Set to true
if mutations to not just target, but also target's descendants are to be observed.
-
-
- attributeOldValue
- Set to true
if attributes
is set to true
and target's attribute value before the mutation needs to be recorded.
-
-
- characterDataOldValue
- Set to true
if characterData
is set to true
and target's data before the mutation needs to be recorded.
-
-
- attributeFilter
- Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.
-
-
-
-
-MutationRecord
-
-MutationRecord
is the object that will be passed to the observer's callback. It has the following properties:
-
-
-
-
-
-
-
-
-
- type
- String
- Returns attributes
if the mutation was an attribute mutation, characterData
if it was a mutation to a CharacterData
node, and childList
if it was a mutation to the tree of nodes.
-
-
- target
- {{domxref("Node")}}
- Returns the node the mutation affected, depending on the type
. For attributes
, it is the element whose attribute changed. For characterData
, it is the CharacterData
node. For childList
, it is the node whose children changed.
-
-
- addedNodes
- {{domxref("NodeList")}}
- Return the nodes added. Will be an empty NodeList
if no nodes were added.
-
-
- removedNodes
- {{domxref("NodeList")}}
- Return the nodes removed. Will be an empty NodeList
if no nodes were removed.
-
-
- previousSibling
- {{domxref("Node")}}
- Return the previous sibling of the added or removed nodes, or null
.
-
-
- nextSibling
- {{domxref("Node")}}
- Return the next sibling of the added or removed nodes, or null
.
-
-
- attributeName
- String
- Returns the local name of the changed attribute, or null
.
-
-
- attributeNamespace
- String
- Returns the namespace of the changed attribute, or null
.
-
-
- oldValue
- String
- The return value depends on the type
. For attributes
, it is the value of the changed attribute before the change. For characterData
, it is the data of the changed node before the change. For childList
, it is null
.
-
-
-
-
-Example usage
-
-The following example was taken from this blog post .
-
-// select the target node
+```
+
+#### Parameters
+
+- `target`
+ - : The {{domxref("Node")}} on which to observe DOM mutations.
+- `options`
+ - : A [`MutationObserverInit`](#MutationObserverInit) object, specifies which DOM mutations should be reported.
+
+> **備註:** Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it.
+
+### `disconnect()`
+
+Stops the `MutationObserver` instance from receiving notifications of DOM mutations. Until the [`observe()`](<#observe()>) method is used again, observer's callback will not be invoked.
+
+```plain
+void disconnect();
+```
+
+### `takeRecords()`
+
+Empties the `MutationObserver` instance's record queue and returns what was in there.
+
+```plain
+Array takeRecords();
+```
+
+#### Return value
+
+Returns an Array of [`MutationRecord`s](#MutationRecord).
+
+## `MutationObserverInit`
+
+`MutationObserverInit` is an object which can specify the following properties:
+
+> **備註:** At the very least, `childList`, `attributes`, or `characterData` must be set to `true`. Otherwise, "An invalid or illegal string was specified" error is thrown.
+
+| Property | Description |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| `childList` | Set to `true` if additions and removals of the target node's child elements (including text nodes) are to be observed. |
+| `attributes` | Set to `true` if mutations to target's attributes are to be observed. |
+| `characterData` | Set to `true` if mutations to target's data are to be observed. |
+| `subtree` | Set to `true` if mutations to not just target, but also target's descendants are to be observed. |
+| `attributeOldValue` | Set to `true` if `attributes` is set to `true` and target's attribute value before the mutation needs to be recorded. |
+| `characterDataOldValue` | Set to `true` if `characterData` is set to `true` and target's data before the mutation needs to be recorded. |
+| `attributeFilter` | Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed. |
+
+## `MutationRecord`
+
+`MutationRecord` is the object that will be passed to the observer's callback. It has the following properties:
+
+| Property | Type | Description |
+| -------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `type` | `String` | Returns `attributes` if the mutation was an attribute mutation, `characterData` if it was a mutation to a `CharacterData` node, and `childList` if it was a mutation to the tree of nodes. |
+| `target` | `{{domxref("Node")}}` | Returns the node the mutation affected, depending on the `type`. For `attributes`, it is the element whose attribute changed. For `characterData`, it is the `CharacterData` node. For `childList`, it is the node whose children changed. |
+| `addedNodes` | `{{domxref("NodeList")}}` | Return the nodes added. Will be an empty `NodeList` if no nodes were added. |
+| `removedNodes` | `{{domxref("NodeList")}}` | Return the nodes removed. Will be an empty `NodeList` if no nodes were removed. |
+| `previousSibling` | `{{domxref("Node")}}` | Return the previous sibling of the added or removed nodes, or `null`. |
+| `nextSibling` | `{{domxref("Node")}}` | Return the next sibling of the added or removed nodes, or `null`. |
+| `attributeName` | `String` | Returns the local name of the changed attribute, or `null`. |
+| `attributeNamespace` | `String` | Returns the namespace of the changed attribute, or `null`. |
+| `oldValue` | `String` | The return value depends on the `type`. For `attributes`, it is the value of the changed attribute before the change. For `characterData`, it is the data of the changed node before the change. For `childList`, it is `null`. |
+
+## Example usage
+
+The following example was taken from [this blog post](http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/).
+
+```js
+// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
@@ -208,18 +128,16 @@ observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
-
+```
-Additional reading
+## Additional reading
-
+- [A brief overview](http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers)
+- [A more in-depth discussion](http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/)
+- [A screencast by Chromium developer Rafael Weinstein](http://www.youtube.com/watch?v=eRZ4pO0gVWw)
+- [The mutation summary library](http://code.google.com/p/mutation-summary/)
+- [The DOM standard](http://dom.spec.whatwg.org/#mutation-observers) which defines the `MutationObserver` interface
-Browser compatibility
+## Browser compatibility
{{Compat("api.MutationObserver")}}
diff --git a/files/zh-tw/web/api/namednodemap/index.md b/files/zh-tw/web/api/namednodemap/index.md
index dcc016e234b931..f8a3e05db6140c 100644
--- a/files/zh-tw/web/api/namednodemap/index.md
+++ b/files/zh-tw/web/api/namednodemap/index.md
@@ -3,56 +3,48 @@ title: NamedNodeMap
slug: Web/API/NamedNodeMap
translation_of: Web/API/NamedNodeMap
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-NamedNodeMap
介面表示了 {{domxref("Attr")}} 物件的集合。雖然 NamedNodeMap
與 {{domxref("NodeList")}} 都能如陣列一般透過索引訪問成員,但和 NodeList
不同的是,NamedNodeMap
中的成員並沒有順序。
+**`NamedNodeMap`** 介面表示了 {{domxref("Attr")}} 物件的集合。雖然 `NamedNodeMap` 與 {{domxref("NodeList")}} 都能如陣列一般透過索引訪問成員,但和 `NodeList` 不同的是,`NamedNodeMap` 中的成員並沒有順序。
-NamedNodeMap
物件具有即時性(live) ,如果其內部成員(屬性節點物件)發生改變,NamedNodeMap
物件會自動更新至最新的狀態。
+`NamedNodeMap` 物件具有*即時性(live)*,如果其內部成員(屬性節點物件)發生改變,`NamedNodeMap` 物件會自動更新至最新的狀態。
-
-
僅管被稱作 NamedNodeMap
,但本介面並不是直接用來處理節點物件({{domxref("Node")}}),而是專門負責屬性節點物件({{domxref("Attr")}})。屬性節點是一種特殊的節點,在部分瀏覽器實作中依然存在。
-
+> **備註:** 僅管被稱作 `NamedNodeMap`,但本介面並不是直接用來處理節點物件({{domxref("Node")}}),而是專門負責屬性節點物件({{domxref("Attr")}})。屬性節點是一種特殊的節點,在部分瀏覽器實作中依然存在。
-屬性
+## 屬性
-This interface doesn't inherit any property.
+_This interface doesn't inherit any property._
-
- {{domxref("NamedNodeMap.length")}} {{ReadOnlyInline}}
- Returns the amount of objects in the map.
-
+- {{domxref("NamedNodeMap.length")}} {{ReadOnlyInline}}
+ - : Returns the amount of objects in the map.
-方法
+## 方法
-This interface doesn't inherit any method.
+_This interface doesn't inherit any method._
-
- {{domxref("NamedNodeMap.getNamedItem()")}}
- Returns a {{domxref("Attr")}}, corresponding to the given name.
- {{domxref("NamedNodeMap.setNamedItem()")}}
- Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given name.
- {{domxref("NamedNodeMap.removeNamedItem()")}}
- Removes the {{domxref("Attr")}} identified by the given map.
- {{domxref("NamedNodeMap.item()")}}
- Returns the {{domxref("Attr")}} at the given index, or null
if the index is higher or equal to the number of nodes.
- {{domxref("NamedNodeMap.getNamedItemNS()")}}
- Returns a {{domxref("Attr")}} identified by a namespace and related local name.
- {{domxref("NamedNodeMap.setNamedItemNS()")}}
- Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given namespace and related local name.
- {{domxref("NamedNodeMap.removeNamedItemNS()")}}
- Removes the {{domxref("Attr")}} identified by the given namespace and related local name.
-
+- {{domxref("NamedNodeMap.getNamedItem()")}}
+ - : Returns a {{domxref("Attr")}}, corresponding to the given name.
+- {{domxref("NamedNodeMap.setNamedItem()")}}
+ - : Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given name.
+- {{domxref("NamedNodeMap.removeNamedItem()")}}
+ - : Removes the {{domxref("Attr")}} identified by the given map.
+- {{domxref("NamedNodeMap.item()")}}
+ - : Returns the {{domxref("Attr")}} at the given index, or `null` if the index is higher or equal to the number of nodes.
+- {{domxref("NamedNodeMap.getNamedItemNS()")}}
+ - : Returns a {{domxref("Attr")}} identified by a namespace and related local name.
+- {{domxref("NamedNodeMap.setNamedItemNS()")}}
+ - : Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given namespace and related local name.
+- {{domxref("NamedNodeMap.removeNamedItemNS()")}}
+ - : Removes the {{domxref("Attr")}} identified by the given namespace and related local name.
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.NamedNodeMap")}}
-參見
+## 參見
-
- {{domxref("Element.attributes")}}
-
+- {{domxref("Element.attributes")}}
diff --git a/files/zh-tw/web/api/navigator/geolocation/index.md b/files/zh-tw/web/api/navigator/geolocation/index.md
index b9953d3b4a560b..e52ac4ac4bc6e2 100644
--- a/files/zh-tw/web/api/navigator/geolocation/index.md
+++ b/files/zh-tw/web/api/navigator/geolocation/index.md
@@ -3,29 +3,26 @@ title: Navigator.geolocation
slug: Web/API/Navigator/geolocation
translation_of: Web/API/Navigator/geolocation
---
-{{APIRef("Geolocation API")}}
+{{APIRef("Geolocation API")}}
-Navigator.geolocation
回傳一個唯讀的 {{domxref("Geolocation")}} 物件,透過這個物件可以存取設備的位置訊息。同時也允許網站或應用程式根據使用者的位置提供客製化的結果。
+**`Navigator.geolocation`** 回傳一個唯讀的 {{domxref("Geolocation")}} 物件,透過這個物件可以存取設備的位置訊息。同時也允許網站或應用程式根據使用者的位置提供客製化的結果。
-
-
備註: 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。
-
+> **備註:** 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。
-語法
+## 語法
-geo = navigator .geolocation
-
+```plain
+geo = navigator.geolocation
+```
-規格
+## 規格
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Navigator.geolocation")}}
-請參考
+## 請參考
-
+- [Using geolocation](/zh-TW/docs/WebAPI/Using_geolocation)
diff --git a/files/zh-tw/web/api/navigator/index.md b/files/zh-tw/web/api/navigator/index.md
index 7a996cebcf6c99..c59da42f570321 100644
--- a/files/zh-tw/web/api/navigator/index.md
+++ b/files/zh-tw/web/api/navigator/index.md
@@ -11,143 +11,131 @@ tags:
- Web Performance
translation_of: Web/API/Navigator
---
-{{ APIRef("DOM4") }}
-
-Navigator
介面標示了用戶代理(user agent)的狀態與身份。它允許腳本查詢與註冊,以進行一些活動。
-
-Navigator
可以被檢索,只要使用唯讀的 {{domxref("window.navigator")}} 屬性。
-
-屬性
-
-它並不繼承任何屬性,但其實做已被定義於 {{domxref("NavigatorID")}}、{{domxref("NavigatorLanguage")}}、{{domxref("NavigatorOnLine")}}、{{domxref("NavigatorContentUtils")}}、{{domxref("NavigatorStorage")}}、{{domxref("NavigatorStorageUtils")}}、{{domxref("NavigatorConcurrentHardware")}}、{{domxref("NavigatorPlugins")}}、{{domxref("NavigatorUserMedia")}}.
-
-標準
-
-
- {{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
- Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is true
).
- {{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
- Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
- {{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
- Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
- {{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
- Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
- {{domxref("Navigator.battery")}} {{readonlyInline}}
- Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
- {{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
- Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.
- {{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
- Returns false if setting a cookie will be ignored and true otherwise.
- {{domxref("Navigator.geolocation")}} {{readonlyInline}}
- Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
- {{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
- Returns the number of logical processor cores available.
- {{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
- Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
- {{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
- Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null
value is returned when this is unknown.
- {{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
- Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
- {{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
- Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
- {{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
- Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
- {{domxref("Navigator.oscpu")}}
- Returns a string that represents the current operating system.
- {{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
- Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the Permissions API .
- {{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
- Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
- {{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
- Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
- {{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
- Always returns 'Gecko'
, on any browser. This property is kept only for compatibility purpose.
- {{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
- Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document .
- {{domxref("Navigator.storage")}} {{readonlyinline}}
- Returns the singleton {{domxref('StorageManager')}} object used for managing persistance permissions and estimating available storage on a site-by-site/app-by-app basis.
- {{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
- Returns the user agent string for the current browser.
-
-
-Non-standard
-
-
-
-
- {{domxref("Navigator.buildID")}} {{non-standard_inline}}
- Returns the build identifier of the browser (e.g., "2006090803").
- {{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
- Returns a boolean indicating whether cookies are enabled in the browser or not.
- {{domxref("Navigator.credentials")}} {{non-standard_inline}}
- Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out.
- {{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
- Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
- {{domxref("Navigator.id")}} {{non-standard_inline}}
- Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for BrowserID to your web site.
- {{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
- Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
- {{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
- {{domxref("Navigator.webkitNotification")}}
- Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
- {{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
- The Object, returned by the navigator.mozSocial
property, is available within the social media provider's panel to provide functionality it may need.
- {{domxref("Navigator.presentation")}} {{non-standard_inline}}
- Returns a reference to the {{domxref("Presentation")}} API.
- {{domxref("Navigator.productSub")}} {{non-standard_inline}}
- Returns the build number of the current browser (e.g., "20060909").
- {{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
- Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
- {{domxref("Navigator.standalone")}} {{non-standard_inline}}
- Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
- {{domxref("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}
- Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.
- {{domxref("Navigator.vendor")}} {{non-standard_inline}}
- Returns the vendor name of the current browser (e.g., "Netscape6").
- {{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
- Returns the vendor version number (e.g. "6.1").
- {{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
- Returns a PointerLock object for the Mouse Lock API .
-
-
-方法
-
-Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.
-
-Standard
-
-
- {{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
- Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
- {{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}
- After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
- {{domxref("Navigator.registerContentHandler()")}}
- Allows web sites to register themselves as a possible handler for a given MIME type.
- {{domxref("Navigator.registerProtocolHandler()")}}
- Allows web sites to register themselves as a possible handler for a given protocol.
- {{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
- Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
- {{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
- Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
- {{domxref("Navigator.share()")}}{{experimental_inline}}
- Invokes the native sharing mechanism of the current platform.
- {{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{experimental_inline}}
- Returns false
. JavaScript taint/untaint functions removed in JavaScript 1.2.
- {{domxref("Navigator.vibrate()")}}
- Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
-
-
-Non-standard
-
-
-
-
- {{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}
- Lets code check to see if the document at a given URI is available without using the network.
- {{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
- Allows in-app payment.
-
+{{ APIRef("DOM4") }}
+
+**`Navigator`** 介面標示了用戶代理(user agent)的狀態與身份。它允許腳本查詢與註冊,以進行一些活動。
+
+`Navigator` 可以被檢索,只要使用唯讀的 {{domxref("window.navigator")}} 屬性。
+
+## 屬性
+
+_它並不繼承任何屬性,但其實做已被定義於 {{domxref("NavigatorID")}}、{{domxref("NavigatorLanguage")}}、{{domxref("NavigatorOnLine")}}、{{domxref("NavigatorContentUtils")}}、{{domxref("NavigatorStorage")}}、{{domxref("NavigatorStorageUtils")}}、{{domxref("NavigatorConcurrentHardware")}}、{{domxref("NavigatorPlugins")}}、{{domxref("NavigatorUserMedia")}}._
+
+### 標準
+
+- {{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is `true`).
+- {{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
+- {{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
+- {{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
+- {{domxref("Navigator.battery")}} {{readonlyInline}}
+ - : Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
+- {{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+ - : Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.
+- {{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
+ - : Returns false if setting a cookie will be ignored and true otherwise.
+- {{domxref("Navigator.geolocation")}} {{readonlyInline}}
+ - : Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+- {{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+ - : Returns the number of logical processor cores available.
+- {{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+- {{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+ - : Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The `null` value is returned when this is unknown.
+- {{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+ - : Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+- {{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+- {{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+ - : Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+- {{domxref("Navigator.oscpu")}}
+ - : Returns a string that represents the current operating system.
+- {{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+ - : Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the [Permissions API](/zh-TW/docs/Web/API/Permissions_API).
+- {{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
+- {{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+ - : Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+- {{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+ - : Always returns `'Gecko'`, on any browser. This property is kept only for compatibility purpose.
+- {{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+ - : Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window).
+- {{domxref("Navigator.storage")}} {{readonlyinline}}
+ - : Returns the singleton {{domxref('StorageManager')}} object used for managing persistance permissions and estimating available storage on a site-by-site/app-by-app basis.
+- {{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+ - : Returns the user agent string for the current browser.
+
+### Non-standard
+
+> **備註:** Firefox OS devices adds more non-standard properties. You can consult them on the [Firefox OS Navigator extensions article](/zh-TW/docs/Mozilla/Firefox_OS/API/Navigator).
+
+- {{domxref("Navigator.buildID")}} {{non-standard_inline}}
+ - : Returns the build identifier of the browser (e.g., "2006090803").
+- {{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
+ - : Returns a boolean indicating whether cookies are enabled in the browser or not.
+- {{domxref("Navigator.credentials")}} {{non-standard_inline}}
+ - : Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out.
+- {{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
+ - : Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
+- {{domxref("Navigator.id")}} {{non-standard_inline}}
+ - : Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for [BrowserID](/zh-TW/docs/BrowserID) to your web site.
+- {{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
+ - : Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
+- {{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("Navigator.webkitNotification")}}
+ - : Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+- {{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
+ - : The Object, returned by the `navigator.mozSocial` property, is available within the social media provider's panel to provide functionality it may need.
+- {{domxref("Navigator.presentation")}} {{non-standard_inline}}
+ - : Returns a reference to the {{domxref("Presentation")}} API.
+- {{domxref("Navigator.productSub")}} {{non-standard_inline}}
+ - : Returns the build number of the current browser (e.g., "20060909").
+- {{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+ - : Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+- {{domxref("Navigator.standalone")}} {{non-standard_inline}}
+ - : Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+- {{domxref("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}
+ - : Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.
+- {{domxref("Navigator.vendor")}} {{non-standard_inline}}
+ - : Returns the vendor name of the current browser (e.g., "Netscape6").
+- {{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
+ - : Returns the vendor version number (e.g. "6.1").
+- {{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
+ - : Returns a PointerLock object for the [Mouse Lock API](/zh-TW/docs/API/Pointer_Lock_API).
+
+## 方法
+
+_Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, _{{domxref("NavigatorUserMedia")}},_ and {{domxref("NavigatorStorageUtils")}}._
+
+### Standard
+
+- {{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
+ - : Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+- {{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}
+ - : After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+- {{domxref("Navigator.registerContentHandler()")}}
+ - : Allows web sites to register themselves as a possible handler for a given MIME type.
+- {{domxref("Navigator.registerProtocolHandler()")}}
+ - : Allows web sites to register themselves as a possible handler for a given protocol.
+- {{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
+ - : Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+- {{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
+ - : Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
+- {{domxref("Navigator.share()")}}{{experimental_inline}}
+ - : Invokes the native sharing mechanism of the current platform.
+- {{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{experimental_inline}}
+ - : Returns `false`. JavaScript taint/untaint functions removed in JavaScript 1.2.
+- {{domxref("Navigator.vibrate()")}}
+ - : Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+### Non-standard
+
+> **備註:** Firefox OS devices adds more non-standard methods. You can consult them on the [Firefox OS Navigator extensions article](/zh-TW/docs/Mozilla/Firefox_OS/API/Navigator).
+
+- {{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}
+ - : Lets code check to see if the document at a given URI is available without using the network.
+- {{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
+ - : Allows in-app payment.
diff --git a/files/zh-tw/web/api/navigator/registerprotocolhandler/index.md b/files/zh-tw/web/api/navigator/registerprotocolhandler/index.md
index 44ea040ee83840..c261732952dec7 100644
--- a/files/zh-tw/web/api/navigator/registerprotocolhandler/index.md
+++ b/files/zh-tw/web/api/navigator/registerprotocolhandler/index.md
@@ -3,105 +3,95 @@ title: Navigator.registerProtocolHandler()
slug: Web/API/Navigator/registerProtocolHandler
translation_of: Web/API/Navigator/registerProtocolHandler
---
-{{APIRef("HTML DOM")}}
-
-In progress. Allows web sites to register themselves as possible handlers for particular protocols.
-
-For security reasons, by default, web sites may only register protocol handlers for themselves — the domain and protocol of the handler must match the current site. However, users may set a preference in Firefox to allow cross website installation, by setting the gecko.handlerService.allowRegisterFromDifferentHost
pref to true
in about:config.
-
-Extensions can register protocol handlers targeting other sites: see the 'See Also' section for how to use them from XPCOM.
-
-Syntax
-
-window.navigator.registerProtocolHandler(protocol , url , title );
-
-
-Parameters
-
-
- protocol
- The protocol the site wishes to handle, specified as a string. For example, you can register to handle SMS text message links by registering to handle the "sms" scheme.
- url
- The URL of the handler, as a string. This string should include "%s" as a placeholder which will be replaced with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone number, email address, or so forth.
- The handler's URL must use one of "http" or "https" as its scheme.
-
- title
- A user-readable title string for the protocol handler. This will be displayed to the user in interface objects as needed.
-
-
-Exceptions
-
-
- SecurityError
- The user agent blocked registration of the protocol handler. This might happen if an invalid scheme is specified, such as "http", which cannot be registered for obvious security reasons.
- SyntaxError
- The "%s" string is missing from the specified protocol handler URL.
-
-
-Permitted schemes
-
-For security reasons, registerProtocolHandler()
has restrictions on which schemes may be registered. A custom scheme may be registered as long as the scheme's name begins with "web+", is at least five characters long (including the "web+" prefix), and has only lower-case ASCII letters in its name. For example, "web+burger", as shown in the Example below.
-
-Otherwise, the scheme must be one of the schemes on the whitelist below:
-
-
-
- bitcoin
- geo
- im
- irc
- ircs
- magnet
- mailto
- mms
- news
- nntp
- sip
- sms
- smsto
- ssh
- tel
- urn
- webcal
- wtai
- xmpp
-
-
-
-Example
-
-If your web application is located at http://www.google.co.uk
, you can register a protocol handler for it to handle "web+burger" links like this:
-
-navigator.registerProtocolHandler("web+burger",
+{{APIRef("HTML DOM")}}
+
+In progress. Allows web sites to register themselves as possible handlers for particular protocols.
+
+For security reasons, by default, web sites may only register protocol handlers for themselves — the domain and protocol of the handler must match the current site. However, users may set a preference in Firefox to allow cross website installation, by setting the `gecko.handlerService.allowRegisterFromDifferentHost` pref to `true` in about:config.
+
+Extensions can register protocol handlers targeting other sites: see the 'See Also' section for how to use them from XPCOM.
+
+## Syntax
+
+```plain
+window.navigator.registerProtocolHandler(protocol, url, title);
+```
+
+### Parameters
+
+- `protocol`
+ - : The protocol the site wishes to handle, specified as a string. For example, you can register to handle SMS text message links by registering to handle the "sms" scheme.
+- `url`
+ - : The URL of the handler, as a string. This string should include "%s" as a placeholder which will be replaced with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone number, email address, or so forth.
+
+ > **備註:** The handler's URL must use one of "http" or "https" as its scheme.
+- `title`
+ - : A user-readable title string for the protocol handler. This will be displayed to the user in interface objects as needed.
+
+### Exceptions
+
+- `SecurityError`
+ - : The user agent blocked registration of the protocol handler. This might happen if an invalid scheme is specified, such as "http", which cannot be registered for obvious security reasons.
+- `SyntaxError`
+ - : The "%s" string is missing from the specified protocol handler URL.
+
+## Permitted schemes
+
+For security reasons, `registerProtocolHandler()` has restrictions on which schemes may be registered. A custom scheme may be registered as long as the scheme's name begins with "web+", is at least five characters long (including the "web+" prefix), and has only lower-case ASCII letters in its name. For example, "web+burger", as shown in the [Example](#example) below.
+
+Otherwise, the scheme must be one of the schemes on the whitelist below:
+
+- `bitcoin`
+- `geo`
+- `im`
+- `irc`
+- `ircs`
+- `magnet`
+- `mailto`
+- `mms`
+- `news`
+- `nntp`
+- `sip`
+- `sms`
+- `smsto`
+- `ssh`
+- `tel`
+- `urn`
+- `webcal`
+- `wtai`
+- `xmpp`
+
+## Example
+
+If your web application is located at `http://www.google.co.uk`, you can register a protocol handler for it to handle "web+burger" links like this:
+
+```js
+navigator.registerProtocolHandler("web+burger",
"https://www.google.co.uk/?uri=%s",
"Burger handler");
-
+```
-This creates a handler that allows web+burger://
links to direct the user to your web application, inserting the burger information specified in the link into the URL. Recall that this script must be run from the same domain (so any page location at google.co.uk
) and the second argument passed must be of http
or https
scheme (in this example it is https
) .
+This creates a handler that allows `web+burger://` links to direct the user to your web application, inserting the burger information specified in the link into the URL. Recall that this script must be run from the same domain (so any page location at `google.co.uk`) and the second argument passed must be of `http` or `https` scheme (in this example it is `https`) .
-The user will be notified that your code has asked to register the protocol handler, so that they can decide whether or not to permit it. See the screenshot below for an example.
+The user will be notified that your code has asked to register the protocol handler, so that they can decide whether or not to permit it. See the screenshot below for an example.
-
+![](protocolregister.png)
-
+> **備註:** "[Register a webmail service as mailto handler](/zh-TW/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWebContentHandlerRegistrar#Getting_most_recent_window)" shows how to do this from XPCOM scope.
-Specifications
+## Specifications
{{Specifications}}
-Browser compatibility
+## Browser compatibility
{{Compat("api.Navigator.registerProtocolHandler")}}
-See also
+## See also
-
+- [Web-based protocol handlers](/zh-TW/docs/Web-based_protocol_handlers)
+- [Navigator.registerContentHandler()](/zh-TW/docs/Web/API/Navigator/registerContentHandler)
+- [RegisterProtocolHandler Enhancing the Federated Web](http://blog.mozilla.com/webdev/2010/07/26/registerprotocolhandler-enhancing-the-federated-web/) at Mozilla Webdev
+- [Web Application APIs - Custom scheme and content handlers](https://html.spec.whatwg.org/multipage/system-state.html#custom-handlers)
+- [Register a webmail service as mailto handler](/zh-TW/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWebContentHandlerRegistrar#Getting_most_recent_window) shows how to do `registerProtocolHandler` from XPCOM scope.
+- [XPCOM Interface Reference > nsIWebContentHandlerRegistrar > registerContentHandler](/zh-TW/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWebContentHandlerRegistrar#registerProtocolHandler) - This shows how to use this function XPCOM scope
diff --git a/files/zh-tw/web/api/node/childnodes/index.md b/files/zh-tw/web/api/node/childnodes/index.md
index 3df258ac10681d..9b5dc940186670 100644
--- a/files/zh-tw/web/api/node/childnodes/index.md
+++ b/files/zh-tw/web/api/node/childnodes/index.md
@@ -3,64 +3,64 @@ title: Node.childNodes
slug: Web/API/Node/childNodes
translation_of: Web/API/Node/childNodes
---
-
+{{APIRef("DOM")}}
-Node.childNodes
唯讀屬性會回傳一個即時更新的動態集合(live collection) ,其包含了指定元素的子{{domxref("Node","節點")}},而第一個子節點會被指派為索引 0。
+**`Node.childNodes`** 唯讀屬性會回傳一個*即時更新的動態集合(live collection)*,其包含了指定元素的子{{domxref("Node","節點")}},而第一個子節點會被指派為索引 0。
-語法
+## 語法
-var ndList = elementNodeReference.childNodes;
-
+```plain
+var ndList = elementNodeReference.childNodes;
+```
-ndList 是一個 {{domxref("NodeList")}},為一個有順序性、由目前元素之 DOM 子節點組成之集合。假如目前元素沒有子節點,則 ndList 會是空的。
+_ndList_ 是一個 {{domxref("NodeList")}},為一個有順序性、由目前元素之 DOM 子節點組成之集合。假如目前元素沒有子節點,則 _ndList_ 會是空的。
-範例
+範例
-// parg is an object reference to a <p> element
+```js
+// parg is an object reference to a element
// First check that the element has child nodes
if (parg.hasChildNodes()) {
var children = parg.childNodes;
- for (var i = 0; i < children.length; i++) {
+ for (var i = 0; i < children.length; i++) {
// do something with each child as children[i]
// NOTE: List is live, adding or removing children will change the list
}
-}
+}
+```
-
-// This is one way to remove all children from a node
+---
+
+```js
+// This is one way to remove all children from a node
// box is an object reference to an element
while (box.firstChild) {
//The list is LIVE so it will re-index each call
box.removeChild(box.firstChild);
-}
+}
+```
-備註
+## 備註
-The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName
to get the name, etc.).
+The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. `elementNodeReference.childNodes[1].nodeName` to get the name, etc.).
-The document
object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement
. (In (X)HTML documents this is the HTML
element.)
+The `document` object itself has 2 children: the Doctype declaration and the root element, typically referred to as `documentElement`. (In (X)HTML documents this is the `HTML` element.)
-childNodes
includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use {{ domxref("ParentNode.children") }} instead.
+`childNodes` includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use {{ domxref("ParentNode.children") }} instead.
-規範
+## 規範
-
+- [W3C DOM 2 Core: childNodes](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987)
+- [W3C DOM 3 Core: childNodes](http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-1451460987)
+- [W3C DOM 3 NodeList interface](http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-536297177)
-參見
+## 參見
-
- {{ domxref("Node.firstChild") }}
- {{ domxref("Node.lastChild") }}
- {{ domxref("Node.nextSibling") }}
- {{ domxref("Node.previousSibling") }}
- {{ domxref("ParentNode.children") }}
-
+- {{ domxref("Node.firstChild") }}
+- {{ domxref("Node.lastChild") }}
+- {{ domxref("Node.nextSibling") }}
+- {{ domxref("Node.previousSibling") }}
+- {{ domxref("ParentNode.children") }}
diff --git a/files/zh-tw/web/api/node/clonenode/index.md b/files/zh-tw/web/api/node/clonenode/index.md
index 36c3d2ee9aa631..486245a2c3038c 100644
--- a/files/zh-tw/web/api/node/clonenode/index.md
+++ b/files/zh-tw/web/api/node/clonenode/index.md
@@ -3,56 +3,52 @@ title: Node.cloneNode()
slug: Web/API/Node/cloneNode
translation_of: Web/API/Node/cloneNode
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-Node.cloneNode()
方法會回傳一個呼叫此方法之節點物件的拷貝。
+**`Node.cloneNode()`** 方法會回傳一個呼叫此方法之節點物件的拷貝。
-語法
+## 語法
-var dupNode = node .cloneNode(deep );
-
+```plain
+var dupNode = node.cloneNode(deep);
+```
-
- node
- The node to be cloned.
- dupNode
- The new node that will be a clone of node
- deep {{optional_inline}}
- true
if the children of the node should also be cloned, or false
to clone only the specified node.
-
+- _node_
+ - : The node to be cloned.
+- _dupNode_
+ - : The new node that will be a clone of `node`
+- _deep {{optional_inline}}_
+ - : `true` if the children of the node should also be cloned, or `false` to clone only the specified node.
-
-
Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep
is an optional argument. If omitted, the method acts as if the value of deep
was true
, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep
must be set to false
.
+> **備註:** In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), `deep` is an optional argument. If omitted, the method acts as if the value of `deep` was **`true`**, defaulting to using deep cloning as the default behavior. To create a shallow clone, `deep` must be set to `false`.This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of `deep` was **`false`**. Though It's still optional, you should always provide the `deep` argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}), the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.
-
This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep
was false
. Though It's still optional, you should always provide the deep
argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}), the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.
-
+## 範例
-範例
-
-var p = document.getElementById("para1");
+```js
+var p = document.getElementById("para1");
var p_prime = p.cloneNode(true);
-
+```
-備註
+## 備註
-Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()
or those assigned to element properties. (e.g. node.onclick = fn
) Moreover, for a <canvas> element, the painted image is not copied.
+Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using [`addEventListener()`](/zh-TW/docs/DOM/element.addEventListener) or those assigned to element properties. (e.g. `node.onclick = fn`) Moreover, for a \ element, the painted image is not copied.
-The duplicate node returned by cloneNode()
is not part of the document until it is added to another node that is part of the document using {{domxref("Node.appendChild()")}} or a similar method. It also has no parent until it is appended to another node.
+The duplicate node returned by `cloneNode()` is not part of the document until it is added to another node that is part of the document using {{domxref("Node.appendChild()")}} or a similar method. It also has no parent until it is appended to another node.
-If deep
is set to false
, child nodes are not cloned. Any text that the node contains is not cloned either, as it is contained in one or more child {{domxref("Text")}} nodes.
+If `deep` is set to `false`, child nodes are not cloned. Any text that the node contains is not cloned either, as it is contained in one or more child {{domxref("Text")}} nodes.
-If deep
evaluates to true
, the whole subtree (including text that may be in child {{domxref("Text")}} nodes) is copied too. For empty nodes (e.g. {{HTMLElement("img")}} and {{HTMLElement("input")}} elements) it doesn't matter whether deep
is set to true
or false
.
+If `deep` evaluates to `true`, the whole subtree (including text that may be in child {{domxref("Text")}} nodes) is copied too. For empty nodes (e.g. {{HTMLElement("img")}} and {{HTMLElement("input")}} elements) it doesn't matter whether `deep` is set to `true` or `false`.
-Warning: cloneNode()
may lead to duplicate element IDs in a document.
+> **警告:** `cloneNode()` may lead to duplicate element IDs in a document.
-If the original node has an ID and the clone is to be placed in the same document, the ID of the clone should be modified to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected.
+If the original node has an ID and the clone is to be placed in the same document, the ID of the clone should be modified to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected.
-To clone a node for appending to a different document, use {{domxref("Document.importNode()")}} instead.
+To clone a node for appending to a different document, use {{domxref("Document.importNode()")}} instead.
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Node.cloneNode")}}
diff --git a/files/zh-tw/web/api/node/index.md b/files/zh-tw/web/api/node/index.md
index a33482713d7f92..814d0ae36501d3 100644
--- a/files/zh-tw/web/api/node/index.md
+++ b/files/zh-tw/web/api/node/index.md
@@ -12,249 +12,199 @@ tags:
- TopicStub
translation_of: Web/API/Node
---
-{{APIRef("DOM")}}
-
-Node
是一個被多種 DOM 類型繼承的介面,它讓各種類型的 DOM 都能以同樣的方式來操作。如繼承了相同的方法,或能以相同的方式測試。
-
-Node
繼承自 {{domxref("EventTarget")}},而繼承了 Node
的屬性及方法的介面則有:{{domxref("Document")}}、{{domxref("Element")}}、{{domxref("CharacterData")}}(被 {{domxref("Text")}}、{{domxref("Comment")}} 以及 {{domxref("CDATASection")}} 所繼承)、{{domxref("ProcessingInstruction")}}、{{domxref("DocumentFragment")}}、{{domxref("DocumentType")}}、{{domxref("Notation")}}、{{domxref("Entity")}}、{{domxref("EntityReference")}}。
-
-These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.
-
-{{InheritanceDiagram}}
-
-屬性
-
-Inherits properties from its parents {{domxref("EventTarget")}} .[1]
-
-
- {{domxref("Node.baseURI")}} {{readonlyInline}}
- Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'
.
- {{domxref("Node.baseURIObject")}} {{Non-standard_inline()}}
- (Not available to web content.) The read-only nsIURI
object representing the base URI for the element.
- {{domxref("Node.childNodes")}} {{readonlyInline}}
- Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node
change, the {{domxref("NodeList")}} object is automatically updated.
- {{domxref("Node.firstChild")}} {{readonlyInline}}
- Returns a {{domxref("Node")}} representing the first direct child node of the node, or null
if the node has no child.
- {{domxref("Node.lastChild")}} {{readonlyInline}}
- Returns a {{domxref("Node")}} representing the last direct child node of the node, or null
if the node has no child.
- {{domxref("Node.nextSibling")}} {{readonlyInline}}
- Returns a {{domxref("Node")}} representing the next node in the tree, or null
if there isn't such node.
- {{domxref("Node.nodeName")}} {{readonlyInline}}
- Returns a {{domxref("DOMString")}} containing the name of the Node
. The structure of the name will differ with the node type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio'
for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text'
string, or a {{domxref("Document")}} node will have the '#document'
string.
- {{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}
- A nsIPrincipal
representing the node principal.
- {{domxref("Node.nodeType")}}{{readonlyInline}}
- Returns an unsigned short
representing the type of the node. Possible values are:
-
-
-
- Name
- Value
-
-
- ELEMENT_NODE
- 1
-
-
- ATTRIBUTE_NODE
{{deprecated_inline()}}
- 2
-
-
- TEXT_NODE
- 3
-
-
- CDATA_SECTION_NODE
{{deprecated_inline()}}
- 4
-
-
- ENTITY_REFERENCE_NODE
{{deprecated_inline()}}
- 5
-
-
- ENTITY_NODE
{{deprecated_inline()}}
- 6
-
-
- PROCESSING_INSTRUCTION_NODE
- 7
-
-
- COMMENT_NODE
- 8
-
-
- DOCUMENT_NODE
- 9
-
-
- DOCUMENT_TYPE_NODE
- 10
-
-
- DOCUMENT_FRAGMENT_NODE
- 11
-
-
- NOTATION_NODE
{{deprecated_inline()}}
- 12
-
-
-
-
- {{domxref("Node.nodeValue")}}
- Returns / Sets the value of the current node
- {{domxref("Node.ownerDocument")}} {{readonlyInline}}
- Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null
.
- {{domxref("Node.parentNode")}} {{readonlyInline}}
- Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null
.
- {{domxref("Node.parentElement")}} {{readonlyInline}}
- Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null
.
- {{domxref("Node.previousSibling")}} {{readonlyInline}}
- Returns a {{domxref("Node")}} representing the previous node in the tree, or null
if there isn't such node.
- {{domxref("Node.textContent")}}
- Returns / Sets the textual content of an element and all its descendants.
-
-
-Deprecated properties
-
-
- {{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
- Returns a {{domxref("Node")}} object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This has been replaced by {{domxref("Node.getRootNode()")}}.
-
-
-Obsolete properties
-
-
- {{domxref("Node.localName")}} {{Deprecated_Inline}}{{readonlyInline}}
- Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element.
-
-
Note: In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML.
-
-
- {{domxref("Node.namespaceURI")}} {{Deprecated_Inline}}{{readonlyInline}}
- The namespace URI of this node, or null
if it is no namespace.
-
-
Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the https://www.w3.org/1999/xhtml/
namespace in both HTML and XML trees.
-
-
- {{domxref("Node.prefix")}} {{Deprecated_Inline}}{{readonlyInline}}
- Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null
if no prefix is specified.
-
-
-方法
-
-Inherits methods from its parent, {{domxref("EventTarget")}} .[1]
-
-
- {{domxref("Node.appendChild()")}}
- Adds the specified childNode argument as the last child to the current node.
- If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position.
- {{domxref("Node.cloneNode()")}}
- Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
- {{domxref("Node.compareDocumentPosition()")}}
- Compares the position of the current node against another node in any other document.
- {{domxref("Node.contains()")}}
- Returns a {{jsxref("Boolean")}} value indicating whether a node is a descendant of a given node or not.
- {{domxref("Node.getRootNode()")}}
- Returns the context object's root which optionally includes the shadow root if it is available.
- {{domxref("Node.hasChildNodes()")}}
- Returns a {{jsxref("Boolean")}} indicating if the element has any child nodes, or not.
- {{domxref("Node.insertBefore()")}}
- Inserts a {{domxref("Node")}} before the reference node as a child of the current node.
- {{domxref("Node.isDefaultNamespace()")}}
- Accepts a namespace URI as an argument and returns a {{jsxref("Boolean")}} with a value of true
if the namespace is the default namespace on the given node or false
if not.
- {{domxref("Node.isEqualNode()")}}
- Returns a {{jsxref("Boolean")}} which indicates whether or not two nodes are of the same type and all their defining data points match.
- {{domxref("Node.isSameNode()")}}
- Returns a {{jsxref("Boolean")}} value indicating whether or not the two nodes are the same (that is, they reference the same object).
- {{domxref("Node.lookupPrefix()")}}
- Returns a {{domxref("DOMString")}} containing the prefix for a given namespace URI, if present, and null
if not. When multiple prefixes are possible, the result is implementation-dependent.
- {{domxref("Node.lookupNamespaceURI()")}}
- Accepts a prefix and returns the namespace URI associated with it on the given node if found (and null
if not). Supplying null
for the prefix will return the default namespace.
- {{domxref("Node.normalize()")}}
- Clean up all the text nodes under this element (merge adjacent, remove empty).
- {{domxref("Node.removeChild()")}}
- Removes a child node from the current element, which must be a child of the current node.
- {{domxref("Node.replaceChild()")}}
- Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
-
-
-Obsolete methods
-
-
- {{domxref("Node.getFeature()")}} {{Deprecated_Inline}}
- x
- {{domxref("Node.getUserData()")}} {{Deprecated_Inline}}
- Allows a user to get some {{domxref("DOMUserData")}} from the node.
- {{domxref("Node.hasAttributes()")}} {{Deprecated_Inline}}
- Returns a {{jsxref("Boolean")}} indicating if the element has any attributes, or not.
- {{domxref("Node.isSupported()")}} {{Deprecated_Inline}}
- Returns a {{jsxref("Boolean")}} flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
- {{domxref("Node.setUserData()")}} {{Deprecated_Inline}}
- Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
-
-
-範例
-
-Browse all child nodes
-
-The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).
-
-function DOMComb (oParent, oCallback) {
+{{APIRef("DOM")}}
+
+**`Node`** 是一個被多種 DOM 類型繼承的介面,它讓各種類型的 DOM 都能以同樣的方式來操作。如繼承了相同的方法,或能以相同的方式測試。
+
+`Node` 繼承自 {{domxref("EventTarget")}},而繼承了 `Node` 的屬性及方法的介面則有:{{domxref("Document")}}、{{domxref("Element")}}、{{domxref("CharacterData")}}(被 {{domxref("Text")}}、{{domxref("Comment")}} 以及 {{domxref("CDATASection")}} 所繼承)、{{domxref("ProcessingInstruction")}}、{{domxref("DocumentFragment")}}、{{domxref("DocumentType")}}、{{domxref("Notation")}}、{{domxref("Entity")}}、{{domxref("EntityReference")}}。
+
+These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.
+
+{{InheritanceDiagram}}
+
+## 屬性
+
+_Inherits properties from its parents {{domxref("EventTarget")}}_.\[1]
+
+- {{domxref("Node.baseURI")}} {{readonlyInline}}
+ - : Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last `'/'`.
+- {{domxref("Node.baseURIObject")}} {{Non-standard_inline()}}
+ - : (Not available to web content.) The read-only `nsIURI` object representing the base URI for the element.
+- {{domxref("Node.childNodes")}} {{readonlyInline}}
+ - : Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the `Node` change, the {{domxref("NodeList")}} object is automatically updated.
+- {{domxref("Node.firstChild")}} {{readonlyInline}}
+ - : Returns a {{domxref("Node")}} representing the first direct child node of the node, or `null` if the node has no child.
+- {{domxref("Node.lastChild")}} {{readonlyInline}}
+ - : Returns a {{domxref("Node")}} representing the last direct child node of the node, or `null` if the node has no child.
+- {{domxref("Node.nextSibling")}} {{readonlyInline}}
+ - : Returns a {{domxref("Node")}} representing the next node in the tree, or `null` if there isn't such node.
+- {{domxref("Node.nodeName")}} {{readonlyInline}}
+ - : Returns a {{domxref("DOMString")}} containing the name of the `Node`. The structure of the name will differ with the node type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like `'audio'` for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the `'#text'` string, or a {{domxref("Document")}} node will have the `'#document'` string.
+- {{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}
+ - : A `nsIPrincipal` representing the node principal.
+- {{domxref("Node.nodeType")}}{{readonlyInline}}
+ - | : Returns an `unsigned short` representing the type of the node. Possible values are: | Name | Value |
+ | ------------------------------------------------------------------------------------- | ---- | ----- |
+ | `ELEMENT_NODE` | `1` |
+ | `ATTRIBUTE_NODE` {{deprecated_inline()}} | `2` |
+ | `TEXT_NODE` | `3` |
+ | `CDATA_SECTION_NODE` {{deprecated_inline()}} | `4` |
+ | `ENTITY_REFERENCE_NODE` {{deprecated_inline()}} | `5` |
+ | `ENTITY_NODE` {{deprecated_inline()}} | `6` |
+ | `PROCESSING_INSTRUCTION_NODE` | `7` |
+ | `COMMENT_NODE` | `8` |
+ | `DOCUMENT_NODE` | `9` |
+ | `DOCUMENT_TYPE_NODE` | `10` |
+ | `DOCUMENT_FRAGMENT_NODE` | `11` |
+ | `NOTATION_NODE` {{deprecated_inline()}} | `12` |
+- {{domxref("Node.nodeValue")}}
+ - : Returns / Sets the value of the current node
+- {{domxref("Node.ownerDocument")}} {{readonlyInline}}
+ - : Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns `null`.
+- {{domxref("Node.parentNode")}} {{readonlyInline}}
+ - : Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns `null`.
+- {{domxref("Node.parentElement")}} {{readonlyInline}}
+ - : Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns `null`.
+- {{domxref("Node.previousSibling")}} {{readonlyInline}}
+ - : Returns a {{domxref("Node")}} representing the previous node in the tree, or `null` if there isn't such node.
+- {{domxref("Node.textContent")}}
+ - : Returns / Sets the textual content of an element and all its descendants.
+
+### Deprecated properties
+
+- {{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
+ - : Returns a {{domxref("Node")}} object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This has been replaced by {{domxref("Node.getRootNode()")}}.
+
+### Obsolete properties
+
+- {{domxref("Node.localName")}} {{Deprecated_Inline}}{{readonlyInline}}
+ - : Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element.
+
+ > **備註:** In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML.
+- {{domxref("Node.namespaceURI")}} {{Deprecated_Inline}}{{readonlyInline}}
+ - : The namespace URI of this node, or `null` if it is no namespace.
+
+ > **備註:** In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the [`https://www.w3.org/1999/xhtml/`](https://www.w3.org/1999/xhtml/) namespace in both HTML and XML trees.
+- {{domxref("Node.prefix")}} {{Deprecated_Inline}}{{readonlyInline}}
+ - : Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or `null` if no prefix is specified.
+
+## 方法
+
+_Inherits methods from its parent, {{domxref("EventTarget")}}_.\[1]
+
+- {{domxref("Node.appendChild()")}}
+ - : Adds the specified childNode argument as the last child to the current node.
+ If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position.
+- {{domxref("Node.cloneNode()")}}
+ - : Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+- {{domxref("Node.compareDocumentPosition()")}}
+ - : Compares the position of the current node against another node in any other document.
+- {{domxref("Node.contains()")}}
+ - : Returns a {{jsxref("Boolean")}} value indicating whether a node is a descendant of a given node or not.
+- {{domxref("Node.getRootNode()")}}
+ - : Returns the context object's root which optionally includes the shadow root if it is available.
+- {{domxref("Node.hasChildNodes()")}}
+ - : Returns a {{jsxref("Boolean")}} indicating if the element has any child nodes, or not.
+- {{domxref("Node.insertBefore()")}}
+ - : Inserts a {{domxref("Node")}} before the reference node as a child of the current node.
+- {{domxref("Node.isDefaultNamespace()")}}
+ - : Accepts a namespace URI as an argument and returns a {{jsxref("Boolean")}} with a value of `true` if the namespace is the default namespace on the given node or `false` if not.
+- {{domxref("Node.isEqualNode()")}}
+ - : Returns a {{jsxref("Boolean")}} which indicates whether or not two nodes are of the same type and all their defining data points match.
+- {{domxref("Node.isSameNode()")}}
+ - : Returns a {{jsxref("Boolean")}} value indicating whether or not the two nodes are the same (that is, they reference the same object).
+- {{domxref("Node.lookupPrefix()")}}
+ - : Returns a {{domxref("DOMString")}} containing the prefix for a given namespace URI, if present, and `null` if not. When multiple prefixes are possible, the result is implementation-dependent.
+- {{domxref("Node.lookupNamespaceURI()")}}
+ - : Accepts a prefix and returns the namespace URI associated with it on the given node if found (and `null` if not). Supplying `null` for the prefix will return the default namespace.
+- {{domxref("Node.normalize()")}}
+ - : Clean up all the text nodes under this element (merge adjacent, remove empty).
+- {{domxref("Node.removeChild()")}}
+ - : Removes a child node from the current element, which must be a child of the current node.
+- {{domxref("Node.replaceChild()")}}
+ - : Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
+### Obsolete methods
+
+- {{domxref("Node.getFeature()")}} {{Deprecated_Inline}}
+ - : x
+- {{domxref("Node.getUserData()")}} {{Deprecated_Inline}}
+ - : Allows a user to get some {{domxref("DOMUserData")}} from the node.
+- {{domxref("Node.hasAttributes()")}} {{Deprecated_Inline}}
+ - : Returns a {{jsxref("Boolean")}} indicating if the element has any attributes, or not.
+- {{domxref("Node.isSupported()")}} {{Deprecated_Inline}}
+ - : Returns a {{jsxref("Boolean")}} flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+- {{domxref("Node.setUserData()")}} {{Deprecated_Inline}}
+ - : Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
+## 範例
+
+### Browse all child nodes
+
+The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).
+
+```js
+function DOMComb (oParent, oCallback) {
if (oParent.hasChildNodes()) {
for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
DOMComb(oNode, oCallback);
}
}
oCallback.call(oParent);
-}
+}
+```
-Syntax
+#### Syntax
-DOMComb(parentNode, callbackFunction);
+```plain
+DOMComb(parentNode, callbackFunction);
+```
-Description
+#### Description
-Recursively cycle all child nodes of parentNode
and parentNode
itself and execute the callbackFunction
upon them as this
objects.
+Recursively cycle all child nodes of `parentNode` and `parentNode` itself and execute the `callbackFunction` upon them as [`this`](/zh-TW/docs/JavaScript/Reference/Operators/this) objects.
-Parameters
+#### Parameters
-
- parentNode
- The parent node (Node Object
).
- callbackFunction
- The callback function (Function
).
-
+- `parentNode`
+ - : The parent node (`Node Object`).
+- `callbackFunction`
+ - : The callback function ([`Function`](/zh-TW/docs/JavaScript/Reference/Global_Objects/Function)).
-Sample usage
+#### Sample usage
-The following example send to the console.log
the text content of the body:
+The following example send to the `console.log` the text content of the body:
-function printContent () {
+```js
+function printContent () {
if (this.nodeValue) { console.log(this.nodeValue); }
}
onload = function () {
DOMComb(document.body, printContent);
-};
+};
+```
-Remove all children nested within a node
+### Remove all children nested within a node
-Element.prototype.removeAll = function () {
+```js
+Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
-};
+};
+```
-Sample usage
+#### Sample usage
-/* ... an alternative to document.body.innerHTML = "" ... */
-document.body.removeAll();
+```js
+/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+```
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Node")}}
diff --git a/files/zh-tw/web/api/node/insertbefore/index.md b/files/zh-tw/web/api/node/insertbefore/index.md
index fc64e67288be2f..0dd95985722ab6 100644
--- a/files/zh-tw/web/api/node/insertbefore/index.md
+++ b/files/zh-tw/web/api/node/insertbefore/index.md
@@ -3,47 +3,45 @@ title: Node.insertBefore()
slug: Web/API/Node/insertBefore
translation_of: Web/API/Node/insertBefore
---
-
+{{APIRef("DOM")}}
-Node.insertBefore()
方法將一個節點安插在參考節點之前,作為某個特定父節點之子節點。If the given child is a reference to an existing node in the document, insertBefore()
moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
+**`Node.insertBefore()`** 方法將一個節點安插在參考節點之前,作為某個特定父節點之子節點。If the given child is a reference to an existing node in the document, `insertBefore()` moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
-同一個節點並不會同時出現在兩個地方。所以當節點已經有父節點,它會先被移除,然後被插入在新的位置上。The {{domxref("Node.cloneNode()")}} can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode
will not be automatically kept in sync.
+同一個節點並不會同時出現在兩個地方。所以當節點已經有父節點,它會先被移除,然後被插入在新的位置上。The {{domxref("Node.cloneNode()")}} can be used to make a copy of the node before appending it under the new parent. Note that the copies made with `cloneNode` will not be automatically kept in sync.
-若參考節點為 null
, 那需插入的節點就會成為特定父節點的最後一個子節點。
+若參考節點為 `null`, 那需插入的節點就會成為特定父節點的最後一個子節點。
-If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the {{domxref("DocumentFragment")}} are moved into the child list of the specified parent node.
+If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the {{domxref("DocumentFragment")}} are moved into the child list of the specified parent node.
-Syntax
+## Syntax
-var insertedNode = parentNode .insertBefore(newNode , referenceNode );
-
+```plain
+var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+```
-If referenceNode
is null
, the newNode
is inserted at the end of the list of child nodes.
+If `referenceNode` is `null`, the `newNode` is inserted at the end of the list of child nodes.
-
-
referenceNode
並非 可選擇的參數 -- 一定要傳入一個節點
或是 null
。若是傳入失敗或不正確的參數,可能會依不同的瀏覽器版本而有不同的 行為 。
-
+> **備註:** _`referenceNode`_ **並非**可選擇的參數 -- 一定要傳入一個`節點`或是 `null`。若是傳入失敗或不正確的參數,可能會依不同的瀏覽器版本而有[不同的](https://bugzilla.mozilla.org/show_bug.cgi?id=119489)[行為](https://code.google.com/p/chromium/issues/detail?id=419780)。
-Returns
+## Returns
-會回傳新加入的子節點。若該值(newNode
)是{{domxref("DocumentFragment")}}, 則回傳空的 {{domxref("DocumentFragment")}}。
+會回傳新加入的子節點。若該值(`newNode`)是{{domxref("DocumentFragment")}}, 則回傳空的 {{domxref("DocumentFragment")}}。
-Example
+## Example
-<div id="parentElement">
- <span id="childElement">foo bar</span>
-</div>
+```html
+
+ foo bar
+
-<script>
+
+```
-
- insertedNode
被插入的節點,也就是 newNode
。
- parentNode
指定的父節點。
- newNode
被插入的節點。
- referenceNode
參考節點。The node before which newNode
is inserted.
-
+- `insertedNode` 被插入的節點,也就是 `newNode`。
+- `parentNode` 指定的父節點。
+- `newNode` 被插入的節點。
+- `referenceNode` 參考節點。The node before which `newNode` is inserted.
-Example
+## Example
-<div id="parentElement">
- <span id="childElement">foo bar</span>
-</div>
+```html
+
+ foo bar
+
-<script>
-// Create a new, plain <span> element
+
+```
-There is no insertAfter
method. It can be emulated by combining the insertBefore
method with nextSibling
.
+There is no `insertAfter` method. It can be emulated by combining the `insertBefore` method with [`nextSibling`](/en-US/docs/DOM/Node.nextSibling).
-In the previous example, sp1
could be inserted after sp2
using:
+In the previous example, `sp1` could be inserted after `sp2` using:
-parentDiv.insertBefore(sp1, sp2.nextSibling);
+```plain
+parentDiv.insertBefore(sp1, sp2.nextSibling);
+```
-If sp2
does not have a next sibling, then it must be the last child — sp2.nextSibling
returns null
, and sp1
is inserted at the end of the child node list (immediately after sp2
).
+If `sp2` does not have a next sibling, then it must be the last child — `sp2.nextSibling` returns `null`, and `sp1` is inserted at the end of the child node list (immediately after `sp2`).
-Example
+## Example
-Insert an element before the first child element, using the firstChild property.
+Insert an element before the first child element, using the [firstChild](/zh-TW/docs/DOM/Node.firstChild) property.
-// Get a reference to the element in which we want to insert a new node
+```js
+// Get a reference to the element in which we want to insert a new node
var parentElement = document.getElementById('parentElement');
// Get a reference to the first child
var theFirstChild = parentElement.firstChild;
@@ -108,25 +109,23 @@ var newElement = document.createElement("div");
// Insert the new element before the first child
parentElement.insertBefore(newElement, theFirstChild);
-
+```
-When the element does not have a first child, then firstChild
is null
. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child either. Consequently, the new element is the only element, after insertion.
+When the element does not have a first child, then `firstChild` is `null`. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child either. Consequently, the new element is the only element, after insertion.
-Browser compatibility
+## Browser compatibility
-{{Compat("api.Node.insertBefore")}}
+{{Compat("api.Node.insertBefore")}}
-Specifications
+## Specifications
{{Specifications}}
-See also
+## See also
-
- {{domxref("Node.removeChild()")}}
- {{domxref("Node.replaceChild()")}}
- {{domxref("Node.appendChild()")}}
- {{domxref("Node.hasChildNodes()")}}
- {{domxref("Element.insertAdjacentElement()")}}
- {{domxref("ParentNode.prepend()")}}
-
+- {{domxref("Node.removeChild()")}}
+- {{domxref("Node.replaceChild()")}}
+- {{domxref("Node.appendChild()")}}
+- {{domxref("Node.hasChildNodes()")}}
+- {{domxref("Element.insertAdjacentElement()")}}
+- {{domxref("ParentNode.prepend()")}}
diff --git a/files/zh-tw/web/api/nodelist/index.md b/files/zh-tw/web/api/nodelist/index.md
index 1c9b2547b7934b..ac822709454921 100644
--- a/files/zh-tw/web/api/nodelist/index.md
+++ b/files/zh-tw/web/api/nodelist/index.md
@@ -3,81 +3,82 @@ title: NodeList
slug: Web/API/NodeList
translation_of: Web/API/NodeList
---
-{{APIRef("DOM")}}
+{{APIRef("DOM")}}
-NodeList
物件是節點的集合,可藉由 {{domxref("Node.childNodes")}} 屬性以及 {{domxref("document.querySelectorAll()")}} 方法取得。
+**`NodeList`** 物件是節點的集合,可藉由 {{domxref("Node.childNodes")}} 屬性以及 {{domxref("document.querySelectorAll()")}} 方法取得。
-
-
雖然 NodeList
不是 Array
,但仍可以使用 forEach()
方法來進行迭代。一些老舊瀏覽器並未實作此方法。
-
+> **備註:** 雖然 `NodeList` 不是 `Array`,但仍可以使用 `forEach()` 方法來進行迭代。一些老舊瀏覽器並未實作此方法。
-在某些情況下,NodeList
為動態集合(live collection) ,意思是 DOM 的改變會反映於集合。例如,{{domxref("Node.childNodes")}} 便是即時更新(live)的:
+在某些情況下,`NodeList` 為*動態集合(live collection)*,意思是 DOM 的改變會反映於集合。例如,{{domxref("Node.childNodes")}} 便是即時更新(live)的:
-var parent = document.getElementById('parent');
+```js
+var parent = document.getElementById('parent');
var child_nodes = parent.childNodes;
console.log(child_nodes.length); // let's assume "2"
parent.appendChild(document.createElement('div'));
console.log(child_nodes.length); // should output "3"
-
+```
-在其他的情況下,NodeList
是一個靜態的集合(static collection) ,代表任何之後的 DOM 變化都不會影響集合的內容。{{domxref("document.querySelectorAll()")}} 會回傳一個靜態的 NodeList
。
+在其他的情況下,`NodeList` 是一個*靜態的集合(static collection)*,代表任何之後的 DOM 變化都不會影響集合的內容。{{domxref("document.querySelectorAll()")}} 會回傳一個靜態的 `NodeList`。
-當你要選擇如何迭代 NodeList
中的項目時,最好能於心中區分動態與靜態集合,尤其是在取得集合長度(length of the list)的時候。
+當你要選擇如何迭代 `NodeList` 中的項目時,最好能於心中區分動態與靜態集合,尤其是在取得集合長度(length of the list)的時候。
-屬性
+## 屬性
-
- {{domxref("NodeList.length")}}
- The number of nodes in the NodeList
.
-
+- {{domxref("NodeList.length")}}
+ - : The number of nodes in the `NodeList`.
-方法
+## 方法
-
- {{domxref("NodeList.item()")}}
- Returns an item in the list by its index, or null
if the index is out-of-bounds; can be used as an alternative to simply accessing nodeList[idx]
(which instead returns undefined
when idx
is out-of-bounds).
- {{domxref("NodeList.entries()")}}
- Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
- {{domxref("NodeList.forEach()")}}
- Executes a provided function once per NodeList
element.
- {{domxref("NodeList.keys()")}}
- Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all keys of the key/value pairs contained in this object.
- {{domxref("NodeList.values()")}}
- Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all values of the key/value pairs contained in this object.
-
+- {{domxref("NodeList.item()")}}
+ - : Returns an item in the list by its index, or `null` if the index is out-of-bounds; can be used as an alternative to simply accessing `nodeList[idx]` (which instead returns `undefined` when `idx` is out-of-bounds).
+- {{domxref("NodeList.entries()")}}
+ - : Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
+- {{domxref("NodeList.forEach()")}}
+ - : Executes a provided function once per `NodeList` element.
+- {{domxref("NodeList.keys()")}}
+ - : Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all keys of the key/value pairs contained in this object.
+- {{domxref("NodeList.values()")}}
+ - : Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all values of the key/value pairs contained in this object.
-範例
+## 範例
-It's possible to loop over the items in a NodeList
using:
+It's possible to loop over the items in a `NodeList` using:
-for (var i = 0; i < myNodeList.length; ++i) {
+```js
+for (var i = 0; i < myNodeList.length; ++i) {
var item = myNodeList[i]; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
-
+```
-Don't be tempted to use for...in
or for each...in
to enumerate the items in the list, since that will also enumerate the length and item properties of the NodeList
and cause errors if your script assumes it only has to deal with {{domxref("element")}} objects. Also, for..in
is not guaranteed to visit the properties in any particular order.
+Don't be tempted to use [`for...in`](/en-US/docs/JavaScript/Reference/Statements/for...in) or [`for each...in`](/en-US/docs/JavaScript/Reference/Statements/for_each...in) to enumerate the items in the list, since that will also enumerate the length and item properties of the `NodeList` and cause errors if your script assumes it only has to deal with {{domxref("element")}} objects. Also, `for..in` is not guaranteed to visit the properties in any particular order.
-for...of
loops will loop over NodeList
objects correctly:
+[`for...of`](/en-US/docs/JavaScript/Reference/Statements/for...of) loops will loop over `NodeList` objects correctly:
-var list = document.querySelectorAll( 'input[type=checkbox]' );
+```js
+var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
item.checked = true;
-}
+}
+```
-Recent browsers also support iterator methods, {{domxref("NodeList.forEach()", "forEach()")}}, as well as {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, and {{domxref("NodeList.keys()", "keys()")}}
+Recent browsers also support iterator methods, {{domxref("NodeList.forEach()", "forEach()")}}, as well as {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, and {{domxref("NodeList.keys()", "keys()")}}
-There is also an Internet Explorer compatible way to use {{jsxref("Array.forEach()", "Array.prototype.forEach")}} for iteration.
+There is also an Internet Explorer compatible way to use {{jsxref("Array.forEach()", "Array.prototype.forEach")}} for iteration.
-var list = document.querySelectorAll( 'input[type=checkbox]' );
+```js
+var list = document.querySelectorAll( 'input[type=checkbox]' );
Array.prototype.forEach.call(list, function (item) {
item.checked = true;
-});
+});
+```
-NodeList 原型
+## NodeList 原型
-You can also add prototypes to nodelist:
+You can also add prototypes to nodelist:
-var elements = document.querySelectorAll(".suggestions");
+```js
+var elements = document.querySelectorAll(".suggestions");
NodeList.prototype.addEventListener = function(event, func) {
this.forEach(function(content, item) {
@@ -94,14 +95,15 @@ elements.addEventListener("click", log);
elements.addEventListener("click", function() {
console.log(this, " awas clicked");
});
-// output from both will be element was clicked the element would be HTML Element
+// output from both will be element was clicked the element would be HTML Element
+```
-For information about forEach see Array.prototype.forEach()
+For information about forEach see [Array.prototype.forEach()](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.NodeList")}}
diff --git a/files/zh-tw/web/api/notifications_api/index.md b/files/zh-tw/web/api/notifications_api/index.md
index 1cde1e2bf7d53c..f974416eb85968 100644
--- a/files/zh-tw/web/api/notifications_api/index.md
+++ b/files/zh-tw/web/api/notifications_api/index.md
@@ -3,75 +3,69 @@ title: Notifications API
slug: Web/API/Notifications_API
translation_of: Web/API/Notifications_API
---
-{{DefaultAPISidebar("Web Notifications")}}
+{{DefaultAPISidebar("Web Notifications")}}
-Notifications API允許網頁控制向終端用戶顯示系統通知 — 它在網頁瀏覽器的視圖之外,因此使用者切換顯示卡或移至不同的應用程式也能顯示。此 API 設計為在相容於不同平台與現有的通知系統相容。
+Notifications API 允許網頁控制向終端用戶顯示系統通知 — 它在網頁瀏覽器的視圖之外,因此使用者切換顯示卡或移至不同的應用程式也能顯示。此 API 設計為在相容於不同平台與現有的通知系統相容。
-概念與使用方法
+## 概念與使用方法
-在受到支持的平台上,顯示系統通知通常涉及兩件事。 首先,用戶需要授予當前的來源權限才能顯示系統通知,通常在應用程式或網站初始化完成後使用{{domxref("Notification.requestPermission()")}} 方法。
+在受到支持的平台上,顯示系統通知通常涉及兩件事。 首先,用戶需要授予當前的來源權限才能顯示系統通知,通常在應用程式或網站初始化完成後使用{{domxref("Notification.requestPermission()")}} 方法。
-btn.addEventListener('click', function() {
+```js
+btn.addEventListener('click', function() {
let promise = Notification.requestPermission();
// wait for permission
-})
+})
+```
-這不僅是最佳實踐 — 您不應向用戶發送他們不同意的通知,並且在未來瀏覽器將明確禁止沒有響應用戶請求允許通知對話框的通知。Firefox 72 開始已遵循這項約定。使用此方法將產生一個請求對話框,如下所示:
+這不僅是最佳實踐 — 您不應向用戶發送他們不同意的通知,並且在未來瀏覽器將明確禁止沒有響應用戶請求允許通知對話框的通知。Firefox 72 開始已遵循這項約定。使用此方法將產生一個請求對話框,如下所示:
-
+![](https://mdn.mozillademos.org/files/10819/notification-bubble.png)
-用戶可以從此處選擇允許、屏蔽來自此來源的通知,也可以不做選擇。 一旦選定,該設置通常將在當前會話中保持不變。
+用戶可以從此處選擇允許、屏蔽來自此來源的通知,也可以不做選擇。 一旦選定,該設置通常將在當前會話中保持不變。
-
-
注意 : 從 Firefox 44 開始,Notifications 和 Push 的權限已合併。如果授予通知權限則推送也將被啟用。
-
+> **備註:** 從 Firefox 44 開始,Notifications 和 [Push](/zh-TW/docs/Web/API/Push_API) 的權限已合併。如果授予通知權限則推送也將被啟用。
-下一步,使用 {{domxref("Notification.Notification","Notification()")}} 構造函數創建一個新通知。 這必須要傳遞一個標題參數(title),並且可以選擇性的傳遞選擇物件指定諸如文字方向、正文、圖標、撥放通知的聲音等等。
+下一步,使用 {{domxref("Notification.Notification","Notification()")}} 構造函數創建一個新通知。 這必須要傳遞一個標題參數(title),並且可以選擇性的傳遞選擇物件指定諸如文字方向、正文、圖標、撥放通知的聲音等等。
-{{AvailableInWorkers}}
+{{AvailableInWorkers}}
-另外,Notifications API規範指定了 ServiceWorker API 的許多附加功能,以允許服務人員觸發通知。
+另外,Notifications API 規範指定了 [ServiceWorker API](/zh-TW/docs/Web/API/ServiceWorker_API) 的許多附加功能,以允許服務人員觸發通知。
-
+> **備註:** 要了解有關在自己的應用程序中使用通知的更多信息,請閱讀 [Using the Notifications API](/zh-TW/docs/Web/API/Notifications_API/Using_the_Notifications_API)。
-Notifications 介面
+## Notifications 介面
-
- {{domxref("Notification")}}
- 定義一個通知物件。
-
+- {{domxref("Notification")}}
+ - : 定義一個通知物件。
-Service worker 附加功能
+### Service worker 附加功能
-
- {{domxref("ServiceWorkerRegistration")}}
- 包含 {{domxref("ServiceWorkerRegistration.showNotification()")}} 和 {{domxref("ServiceWorkerRegistration.getNotifications()")}} 用於控制通知顯示的方法。
- {{domxref("ServiceWorkerGlobalScope")}}
- 包含 {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} 點擊通知時觸發自定義函數的處理程序。
- {{domxref("NotificationEvent")}}
- 基於 {{domxref("ExtendableEvent")}} 的特定類型的事件對象,它表示已觸發的通知。
-
+- {{domxref("ServiceWorkerRegistration")}}
+ - : 包含 {{domxref("ServiceWorkerRegistration.showNotification()")}} 和 {{domxref("ServiceWorkerRegistration.getNotifications()")}} 用於控制通知顯示的方法。
+- {{domxref("ServiceWorkerGlobalScope")}}
+ - : 包含 {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} 點擊通知時觸發自定義函數的處理程序。
+- {{domxref("NotificationEvent")}}
+ - : 基於 {{domxref("ExtendableEvent")}} 的特定類型的事件對象,它表示已觸發的通知。
-規範
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
{{Compat("api.Notification")}}
-Firefox OS permissions
+## Firefox OS permissions
-When using notifications in a Firefox OS app, be sure to add the desktop-notification
permission in your manifest file. Notifications can be used at any permission level, hosted or above:
+When using notifications in a Firefox OS app, be sure to add the `desktop-notification` permission in your manifest file. Notifications can be used at any permission level, hosted or above:
-"permissions": {
+```json
+"permissions": {
"desktop-notification": {}
-}
+}
+```
-參見
+## 參見
-
+- [Using the Notifications API](/zh-TW/docs/Web/API/Notifications_API/Using_the_Notifications_API)
diff --git a/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.md b/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.md
index d82603df139a3f..fa8c281a98ca0f 100644
--- a/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.md
+++ b/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.md
@@ -3,96 +3,92 @@ title: 使用 Web Notifications
slug: Web/API/Notifications_API/Using_the_Notifications_API
translation_of: Web/API/Notifications_API/Using_the_Notifications_API
---
-{{SeeCompatTable}}
+{{SeeCompatTable}}
-摘要
+## 摘要
-Web Notifications API 可將通知傳送至頁面以外的系統層級並顯示通知。因此即使 Web Apps 處於閒置狀態,亦可傳送資訊予使用者。絕佳範例之一,就是在使用其他 Apps 時,Web Mail App 同樣可通知使用者已接收到新郵件。
+Web Notifications API 可將通知傳送至頁面以外的系統層級並顯示通知。因此即使 Web Apps 處於閒置狀態,亦可傳送資訊予使用者。絕佳範例之一,就是在使用其他 Apps 時,Web Mail App 同樣可通知使用者已接收到新郵件。
-要求權限
+## 要求權限
-網頁內容
+### 網頁內容
-在 Apps 傳送通知之前,使用者必須先許可 Apps 的動作。只要 APIs 嘗試予網頁之外的東西互動,均必須先獲得使用者的授權。如此可避免濫發通知而影響使用經驗。
+在 Apps 傳送通知之前,使用者必須先許可 Apps 的動作。只要 APIs 嘗試予網頁之外的東西互動,均必須先獲得使用者的授權。如此可避免濫發通知而影響使用經驗。
-透過 Notification.permission
唯讀屬性,要傳送通知的 Apps 將檢查目前的授權狀態。此屬性共有 3 組參數:
+透過 [`Notification.permission`](/zh-TW/docs/Web/API/Notification.permission) 唯讀屬性,要傳送通知的 Apps 將檢查目前的授權狀態。此屬性共有 3 組參數:
-
- default:
使用者尚未給予任何權限 (因此不會顯示任何通知)
- granted
:使用者允許接收到 Apps 的通知
- denied
:使用者拒絕接收
Apps 的通知
-
+- `default:`使用者尚未給予任何權限 (因此不會顯示任何通知)
+- `granted`:使用者允許接收到 Apps 的通知
+- ` denied`` :使用者拒絕接收 `Apps 的通知
-
-
注意: Chrome 與 Safari 尚未建構 permission
屬性。
-
+> **備註:** Chrome 與 Safari 尚未建構 `permission` 屬性。
-若使用者尚未給予權限,則 Apps 必須透過 Notification.requestPermission()
函式讓使用者選擇,接著由此函式接收 1 組回呼 (Callback) 函式作為參數;而該回呼函式則提供使用者是否授權的資訊。
+若使用者尚未給予權限,則 Apps 必須透過 [`Notification.requestPermission()`](/zh-TW/docs/Web/API/Notification.requestPermission) 函式讓使用者選擇,接著由此函式接收 1 組回呼 (Callback) 函式作為參數;而該回呼函式則提供使用者是否授權的資訊。
-以下為啟動 Apps 時要求權限的常用範例:
+以下為啟動 Apps 時要求權限的常用範例:
-window.addEventListener('load', function () {
+```js
+window.addEventListener('load', function () {
Notification.requestPermission(function (status) {
// This allows to use Notification.permission with Chrome/Safari
if (Notification.permission !== status) {
Notification.permission = status;
}
});
-});
+});
+```
-
+> **備註:** Chrome 不允許於載入事件中呼叫 [`Notification.requestPermission()`](/zh-TW/docs/Web/API/Notification.requestPermission) (參閱 [issue 274284](https://code.google.com/p/chromium/issues/detail?id=274284))。
-已安裝的 Apps
+### 已安裝的 Apps
-在安裝 Apps 之後,若於 Apps 的 manifest 檔案 中直接添加權限,即可省去再次向使用者要求權限的動作。
+在安裝 Apps 之後,若於 [Apps 的 manifest 檔案](/zh-TW/docs/%E6%87%89%E7%94%A8%E7%A8%8B%E5%BC%8F/Manifest-840092-dup)中直接添加權限,即可省去再次向使用者要求權限的動作。
-permissions: {
+```json
+permissions: {
"desktop-notification": {
"description: "Allows to display notifications on the user's desktop.
}
-}
-
-建立通知
-
-透過 Notification
建構子 (Constructor) 即可建立通知。此建構子包含 1 組標題,可於通知內顯示;另有如 icon
或文字 body
等
數個選項,可強化通知的內容。
+}
+```
-在建立實體 (Instantiated) 之後,就會儘快顯示通知。若要追蹤通知的目前狀態,必須在 Notification
的實體階層觸發 4 個事件:
+## 建立通知
-
- show :對使用者顯示通知之後,隨即觸發
- click :使用者點擊通知之後,隨即觸發
- close :關閉通知之後,隨即觸發
- error :通知發生任何錯誤 (大多數是因為某種情況而未顯示通知),隨即觸發
-
+透過 [`Notification`](/zh-TW/docs/Web/API/Notification) 建構子 (Constructor) 即可建立通知。此建構子包含 1 組標題,可於通知內顯示;另有如 [`icon`](/zh-TW/docs/Web/API/Notification.icon) 或文字 [`body`](/zh-TW/docs/Web/API/Notification.body)` 等`數個選項,可強化通知的內容。
-而透過 onshow
、onclick
、onclose
,或 onerror
等事件處理器 (Event handler),即可追蹤這些事件。由於 Notification
是繼承 EventTarget
而來,因此亦可使用 addEventListener()
函式。
+在建立實體 (Instantiated) 之後,就會儘快顯示通知。若要追蹤通知的目前狀態,必須在 [`Notification`](/zh-TW/docs/Web/API/Notification) 的實體階層觸發 4 個事件:
-
-
注意: Firefox 與 Safari 並未遵守 close 事件的規格。此規格雖然規定「僅限使用者能關閉通知」,但 Firefox 與 Safari 卻可於數分鐘後自動關閉通知。因此不一定是由使用者關閉通知。
+- [show](/zh-TW/docs/Web/Reference/Events/show):對使用者顯示通知之後,隨即觸發
+- [click](/zh-TW/docs/Web/Reference/Events/click):使用者點擊通知之後,隨即觸發
+- [close](/zh-TW/docs/Web/Reference/Events/close):關閉通知之後,隨即觸發
+- [error](/zh-TW/docs/Web/Reference/Events/error):通知發生任何錯誤 (大多數是因為某種情況而未顯示通知),隨即觸發
-
此規格並明確規定「應透過 Notification.close()
函式,於應用程式層級完成自動關閉通知」。範例程式碼如下:
+而透過 [`onshow`](/zh-TW/docs/Web/API/Notification.onshow)、[`onclick`](/zh-TW/docs/Web/API/Notification.onclick)、[`onclose`](/zh-TW/docs/Web/API/Notification.onclose),或 [`onerror`](/zh-TW/docs/Web/API/Notification.onerror) 等事件處理器 (Event handler),即可追蹤這些事件。由於 [`Notification`](/zh-TW/docs/Web/API/Notification) 是繼承 [`EventTarget`](/zh-TW/docs/Web/API/EventTarget) 而來,因此亦可使用 [`addEventListener()`](/zh-TW/docs/Web/API/EventTarget.addEventListener) 函式。
-
var n = new Notification("Hi!");
-n.onshow = function () {
- setTimeout(n.close, 5000);
-}
-
-
+> **備註:** Firefox 與 Safari 並未遵守 close 事件的規格。此規格雖然規定「僅限使用者能關閉通知」,但 Firefox 與 Safari 卻可於數分鐘後自動關閉通知。因此不一定是由使用者關閉通知。此規格並明確規定「應透過 [`Notification.close()`](/zh-TW/docs/Web/API/Notification.close) 函式,於應用程式層級完成自動關閉通知」。範例程式碼如下:
+>
+> ```js
+> var n = new Notification("Hi!");
+> n.onshow = function () {
+> setTimeout(n.close, 5000);
+> }
+> ```
-簡易範例
+### 簡易範例
-先假設下列基本 HTML:
+先假設下列基本 HTML:
-<button>Notify me!</button>
+```html
+Notify me!
+```
-則能以這種方法處理通知:
+則能以這種方法處理通知:
-window.addEventListener('load', function () {
+```js
+window.addEventListener('load', function () {
// At first, let's check if we have permission for notification
// If not, let's ask for it
- if (Notification && Notification.permission !== "granted") {
+ if (Notification && Notification.permission !== "granted") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
@@ -102,13 +98,13 @@ n.onshow = function () {
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', function () {
// If the user agreed to get notified
- if (Notification && Notification.permission === "granted") {
+ if (Notification && Notification.permission === "granted") {
var n = new Notification("Hi!");
}
// If the user hasn't told if he wants to be notified or not
// Note: because of Chrome, we are not sure the permission property
// is set, therefore it's unsafe to check for the "default" value.
- else if (Notification && Notification.permission !== "denied") {
+ else if (Notification && Notification.permission !== "denied") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
@@ -129,32 +125,36 @@ n.onshow = function () {
alert("Hi!");
}
});
-});
+});
+```
-現場測試結果
+### 現場測試結果
-若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
+若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
-{{ EmbedLiveSample('Simple_example', '100%', 30) }}
+{{ EmbedLiveSample('Simple_example', '100%', 30) }}
-處理多筆通知
+## 處理多筆通知
-某些情況下 (如某個即時訊息 App 持續通知每一筆進來的訊息),使用者可能會接收大量的通知。為了避免太多非必要訊息擠爆使用者的桌面,則應該讓等待中的通知進入佇列。
+某些情況下 (如某個即時訊息 App 持續通知每一筆進來的訊息),使用者可能會接收大量的通知。為了避免太多非必要訊息擠爆使用者的桌面,則應該讓等待中的通知進入佇列。
-將標籤添加至任何新的通知,即可達到佇列效果。若通知擁有相同的標籤且尚未顯示,則新通知就會取代先前的通知;反之,若已顯示了相同標籤的通知,就會關閉先前的通知而顯示新通知。
+將標籤添加至任何新的通知,即可達到佇列效果。若通知擁有相同的標籤且尚未顯示,則新通知就會取代先前的通知;反之,若已顯示了相同標籤的通知,就會關閉先前的通知而顯示新通知。
-標籤範例
+### 標籤範例
-先假設下列基本 HTML:
+先假設下列基本 HTML:
-<button>Notify me!</button>
+```html
+Notify me!
+```
-則能以下列方式處理多筆通知:
+則能以下列方式處理多筆通知:
-window.addEventListener('load', function () {
+```js
+window.addEventListener('load', function () {
// At first, let's check if we have permission for notification
// If not, let's ask for it
- if (Notification && Notification.permission !== "granted") {
+ if (Notification && Notification.permission !== "granted") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
@@ -165,8 +165,8 @@ n.onshow = function () {
button.addEventListener('click', function () {
// If the user agreed to get notified
// Let's try to send ten notifications
- if (Notification && Notification.permission === "granted") {
- for (var i = 0; i < 10; i++) {
+ if (Notification && Notification.permission === "granted") {
+ for (var i = 0; i < 10; i++) {
// Thanks to the tag, we should only see the "Hi! 10" notification
var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
}
@@ -174,14 +174,14 @@ n.onshow = function () {
// If the user hasn't told if he wants to be notified or not
// Note: because of Chrome, we are not sure the permission property
// is set, therefore it's unsafe to check for the "default" value.
- else if (Notification && Notification.permission !== "denied") {
+ else if (Notification && Notification.permission !== "denied") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
}
// If the user said okay
if (status === "granted") {
- for (var i = 0; i < 10; i++) {
+ for (var i = 0; i < 10; i++) {
// Thanks to the tag, we should only see the "Hi! 10" notification
var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
}
@@ -198,24 +198,23 @@ n.onshow = function () {
alert(Hi!");
}
});
-});
+});
+```
-現場測試結果
+### 現場測試結果
-若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
+若無法顯示,可至本文右上角「Language」切換回英文原文觀看。
-{{ EmbedLiveSample('Tag_example', '100%', 30) }}
+{{ EmbedLiveSample('Tag_example', '100%', 30) }}
-規格
+## 規格
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
-{{page("/en-US/Web/API/Notification","Browser compatibility")}}
+{{page("/en-US/Web/API/Notification","Browser compatibility")}}
-另可參閱
+## 另可參閱
-
- {{ domxref("Notification") }}
-
+- {{ domxref("Notification") }}
diff --git a/files/zh-tw/web/api/payment_request_api/index.md b/files/zh-tw/web/api/payment_request_api/index.md
index def3f8c31e747f..f51806c349e8e8 100644
--- a/files/zh-tw/web/api/payment_request_api/index.md
+++ b/files/zh-tw/web/api/payment_request_api/index.md
@@ -3,92 +3,79 @@ title: Payment Request API
slug: Web/API/Payment_Request_API
translation_of: Web/API/Payment_Request_API
---
-{{DefaultAPISidebar("Payment Request API")}}{{securecontext_header}}
-
-Payment Request API 提供商家與用戶雙方一致的用戶體驗。它並不是嶄新的支付方式、而是讓用戶選擇偏好的支付方式、並把該方式提供給商家。
-
-Payment Request 的概念和用法
-
-很多放棄線上購物的問題,與結帳表單的填寫有關:填寫這些東西既困難又耗時、步驟還極度繁雜。Payment Request API 正是為減少、甚至擺脫要完成表單所需的填寫步驟而生。它藉由不假手 HTML 表單的情況下,記下要傳給商家的用戶資訊,來簡化結帳步驟。
-
-針對信用卡付款,使用 Payment Request API 的好處有:
-
-
- 快速的訂購體驗 :用戶在進入瀏覽器時輸入資訊、接著就備齊網路購物所需。用戶再也無須於多個網站,填寫相同資訊。
- 各站一致且支援 API 的用戶體驗 :由於是瀏覽器在掌管付款資訊,用戶體驗將能客製化、還可以把 UI 本土化為用戶偏好的語言。
- 無障礙 :由於是瀏覽器在掌管輸入表單,各網站針對鍵盤和螢幕閱讀器的無障礙將確保一致,而無須開發者動工。瀏覽器還能調整輸入表單的字體大小、色彩對比,讓用戶能更輕鬆地完成付款。
- 憑證管理 :用戶能在瀏覽器,管理信用卡與送達地址的資訊。瀏覽器還能跨設備同步這些「憑證」,以便用戶在電腦與手機周旋間,依舊能輕易付款。
- 一致的錯誤處理 :瀏覽器會檢查信用卡號碼、並告訴用戶該卡片(將)過期與否;瀏覽器也可以藉由商家的使用模式或限制(例如「只接受 Visa 卡或萬事達卡(Mastercard)」)自動提示用戶、或允許其選擇偏好的信用卡。
-
-
-要請求支付的話,建立 {{domxref("PaymentRequest")}} 物件的網頁,將回應用戶發動付款的行為,像是點選「購物」按鈕。PaymentRequest
將允許網頁在用戶提供完成交易所需資訊時交換之。
-
-你可以在 使用 Payment Request API 文章看到完整教學。
-
-
-
注意 :此 API 只有在設定 {{htmlattrxref("allowpaymentrequest","iframe")}} 屬性下,才可支援跨域 {{htmlelement("iframe")}} 元素。
-
-
-介面
-
-
- {{domxref('PaymentAddress')}}
- 地址資訊物件,具體用途有付款與送達。
- {{domxref('PaymentRequest')}}
- 提供 API 以便建立與管理{{Glossary("用戶代理")}}的付款介面物件。
- {{domxref('PaymentRequestEvent')}}
- 建立 {{domxref("PaymentRequest")}} 時發送給付款處理器(payment handler)的事件。
- {{domxref('PaymentRequestUpdateEvent')}}
- 允許網頁針對用戶行為,發動更新用戶付款資訊的請求。
- {{domxref('PaymentMethodChangeEvent')}}
- 表示用戶更改付款工具(例如從信用卡轉為簽帳金融卡)。
- {{domxref('PaymentResponse')}}
- 在用戶選取付款方法、並同意付款請求後,所回傳的物件。
- {{domxref('MerchantValidationEvent')}}
- 表示商家(網站)要求使用特定支付方法的瀏覽器驗證處理器(例如:要不要放行 Apple Pay)
-
-
-字詞(dictionary)
-
-
- {{domxref("AddressErrors")}}
- 此字詞包含任何與 {{domxref("PaymentAddress")}} entry 錯誤相關的描述性解釋字串。
- {{domxref("PayerErrors")}}
- 此字詞包含任何與 {{domxref("PaymentResponse")}} 的 email、電話、名字屬性(name attribute)錯誤相關之描述性解釋字串。
- {{domxref("PaymentDetailsUpdate")}}
- 此物件描述伺服器在用戶開始互動前、實例化支付界面後,針對行為需要修改的付款資訊。
-
-
-
-
-
-
- {{domxref("BasicCardChangeDetails")}}
- An object providing redacted address information that is provided as the {{domxref("PaymentMethodChangeEvent.methodDetails", "methodDetails")}} on the {{event("paymentmethodchange")}} event sent to the {{domxref("PaymentRequest")}} when the user changes payment information.
- {{domxref("BasicCardErrors")}}
- An object providing any error messages associated with the fields in the {{domxref("BasicCardResponse")}} object that are not valid. This is used as the value of the {{domxref("PaymentValidationErrors.paymentMethod", "paymentMethod")}} property on the {{domxref("PaymentValidationErrors")}} object sent to the {{domxref("PaymentRequest")}} when an error occurs.
- {{domxref('BasicCardRequest')}}
- Defines an object structure for containing payment request details such as card type.
- {{domxref('BasicCardResponse')}}
- Defines an object structure for payment response details such as the number/expiry date of the card used to make the payment, and the billing address.
-
-
-規範
+{{DefaultAPISidebar("Payment Request API")}}{{securecontext_header}}
+
+Payment Request API 提供商家與用戶雙方一致的用戶體驗。它並不是嶄新的支付方式、而是讓用戶選擇偏好的支付方式、並把該方式提供給商家。
+
+## Payment Request 的概念和用法
+
+很多放棄線上購物的問題,與結帳表單的填寫有關:填寫這些東西既困難又耗時、步驟還極度繁雜。**Payment Request API**正是為減少、甚至擺脫要完成表單所需的填寫步驟而生。它藉由不假手 HTML 表單的情況下,記下要傳給商家的用戶資訊,來簡化結帳步驟。
+
+針對信用卡付款,使用 Payment Request API 的好處有:
+
+- **快速的訂購體驗**:用戶在進入瀏覽器時輸入資訊、接著就備齊網路購物所需。用戶再也無須於多個網站,填寫相同資訊。
+- **各站一致且支援 API 的用戶體驗**:由於是瀏覽器在掌管付款資訊,用戶體驗將能客製化、還可以把 UI 本土化為用戶偏好的語言。
+- **無障礙**:由於是瀏覽器在掌管輸入表單,各網站針對鍵盤和螢幕閱讀器的無障礙將確保一致,而無須開發者動工。瀏覽器還能調整輸入表單的字體大小、色彩對比,讓用戶能更輕鬆地完成付款。
+- **憑證管理**:用戶能在瀏覽器,管理信用卡與送達地址的資訊。瀏覽器還能跨設備同步這些「憑證」,以便用戶在電腦與手機周旋間,依舊能輕易付款。
+- **一致的錯誤處理**:瀏覽器會檢查信用卡號碼、並告訴用戶該卡片(將)過期與否;瀏覽器也可以藉由商家的使用模式或限制(例如「只接受 Visa 卡或萬事達卡(Mastercard)」)自動提示用戶、或允許其選擇偏好的信用卡。
+
+要請求支付的話,建立 {{domxref("PaymentRequest")}} 物件的網頁,將回應用戶發動付款的行為,像是點選「購物」按鈕。`PaymentRequest` 將允許網頁在用戶提供完成交易所需資訊時交換之。
+
+你可以在 [使用 Payment Request API](/zh-TW/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) 文章看到完整教學。
+
+> **備註:** 此 API 只有在設定 {{htmlattrxref("allowpaymentrequest","iframe")}} 屬性下,才可支援跨域 {{htmlelement("iframe")}} 元素。
+
+## 介面
+
+- {{domxref('PaymentAddress')}}
+ - : 地址資訊物件,具體用途有付款與送達。
+- {{domxref('PaymentRequest')}}
+ - : 提供 API 以便建立與管理{{Glossary("用戶代理")}}的付款介面物件。
+- {{domxref('PaymentRequestEvent')}}
+ - : 建立 {{domxref("PaymentRequest")}} 時發送給付款處理器(payment handler)的事件。
+- {{domxref('PaymentRequestUpdateEvent')}}
+ - : 允許網頁針對用戶行為,發動更新用戶付款資訊的請求。
+- {{domxref('PaymentMethodChangeEvent')}}
+ - : 表示用戶更改付款工具(例如從信用卡轉為簽帳金融卡)。
+- {{domxref('PaymentResponse')}}
+ - : 在用戶選取付款方法、並同意付款請求後,所回傳的物件。
+- {{domxref('MerchantValidationEvent')}}
+ - : 表示商家(網站)要求使用特定支付方法的瀏覽器驗證處理器(例如:要不要放行 Apple Pay)
+
+## 字詞(dictionary)
+
+- {{domxref("AddressErrors")}}
+ - : 此字詞包含任何與 {{domxref("PaymentAddress")}} entry 錯誤相關的描述性解釋字串。
+- {{domxref("PayerErrors")}}
+ - : 此字詞包含任何與 {{domxref("PaymentResponse")}} 的 email、電話、名字屬性(name attribute)錯誤相關之描述性解釋字串。
+- {{domxref("PaymentDetailsUpdate")}}
+ - : 此物件描述伺服器在用戶開始互動前、實例化支付界面後,針對行為需要修改的付款資訊。
+
+### Related dictionaries for the Basic Card specification
+
+- {{domxref("BasicCardChangeDetails")}}
+ - : An object providing _redacted_ address information that is provided as the {{domxref("PaymentMethodChangeEvent.methodDetails", "methodDetails")}} on the {{event("paymentmethodchange")}} event sent to the {{domxref("PaymentRequest")}} when the user changes payment information.
+- {{domxref("BasicCardErrors")}}
+ - : An object providing any error messages associated with the fields in the {{domxref("BasicCardResponse")}} object that are not valid. This is used as the value of the {{domxref("PaymentValidationErrors.paymentMethod", "paymentMethod")}} property on the {{domxref("PaymentValidationErrors")}} object sent to the {{domxref("PaymentRequest")}} when an error occurs.
+- {{domxref('BasicCardRequest')}}
+ - : Defines an object structure for containing payment request details such as card type.
+- {{domxref('BasicCardResponse')}}
+ - : Defines an object structure for payment response details such as the number/expiry date of the card used to make the payment, and the billing address.
+
+## 規範
{{Specifications}}
-瀏覽器相容性
+## 瀏覽器相容性
-PaymentRequest 介面
+### PaymentRequest 介面
-{{Compat("api.PaymentRequest", 0)}}
+{{Compat("api.PaymentRequest", 0)}}
-參見
+## 參見
-
+- [使用 Payment Request API](/zh-TW/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
+- [Payment 處理概念](/zh-TW/docs/Web/API/Payment_Request_API/Concepts)
+- [Introducing the Payment Request API for Apple Pay](https://webkit.org/blog/8182/introducing-the-payment-request-api-for-apple-pay/)
+- [Google Pay API PaymentRequest Tutorial](https://developers.google.com/pay/api/web/guides/paymentrequest/tutorial)
+- [W3C Payment Request API FAQ](https://github.com/w3c/payment-request-info/wiki/FAQ)
diff --git a/files/zh-tw/web/api/performance/index.md b/files/zh-tw/web/api/performance/index.md
index fcd342819bf557..a90b83afefd3f8 100644
--- a/files/zh-tw/web/api/performance/index.md
+++ b/files/zh-tw/web/api/performance/index.md
@@ -12,76 +12,64 @@ tags:
- Web Performance
translation_of: Web/API/Performance
---
-{{APIRef("High Resolution Time")}}
-
-The Performance
interface provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API , the Navigation Timing API , the User Timing API , and the Resource Timing API .
-
-An object of this type can be obtained by calling the {{domxref("Window.performance")}} read-only attribute.
-
-
-
This interface and its members are available in Web Workers , except where indicated below. Also note that performance markers and measures are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.
-
-
-Properties
-
-The Performance
interface doesn't inherit any properties.
-
-
- {{deprecated_inline}} {{domxref("Performance.navigation")}} {{readonlyInline}}
- A {{domxref("PerformanceNavigation")}} object that provides useful context about the operations included in the times listed in timing
, including whether the page was a load or a refresh, how many redirections occurred, and so forth.
- {{deprecated_inline}} {{domxref("Performance.timing")}} {{readonlyInline}}
- A {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
- {{domxref("Performance.memory", "performance.memory")}} {{Non-standard_inline}}
- A non-standard extension added in Chrome, this property provides an object with basic memory usage information. You should not use this non-standard API.
- {{domxref("Performance.timeOrigin")}} {{readonlyInline}} {{Non-standard_inline}}
- Returns the high resolution timestamp of the start time of the performance measurement.
-
-
-
-
- Event handlers
-
- {{domxref("Performance.onresourcetimingbufferfull")}}
- An {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
-
-
-Methods
-
-The Performance
interface doesn't inherit any methods .
-
-
- {{domxref("Performance.clearMarks()")}}
- Removes the given mark from the browser's performance entry buffer.
- {{domxref("Performance.clearMeasures()")}}
- Removes the given measure from the browser's performance entry buffer.
- {{domxref("Performance.clearResourceTimings()")}}
- Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "resource
" from the browser's performance data buffer.
- {{domxref("Performance.getEntries()")}}
- Returns a list of {{domxref("PerformanceEntry")}} objects based on the given filter .
- {{domxref("Performance.getEntriesByName()")}}
- Returns a list of {{domxref("PerformanceEntry")}} objects based on the given name and entry type .
- {{domxref("Performance.getEntriesByType()")}}
- Returns a list of {{domxref("PerformanceEntry")}} objects of the given entry type .
- {{domxref("Performance.mark()")}}
- Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer with the given name.
- {{domxref("Performance.measure()")}}
- Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the start mark and end mark , respectively).
- {{domxref("Performance.now()")}}
- Returns a {{domxref("DOMHighResTimeStamp")}} representing the number of milliseconds elapsed since a reference instant.
- {{domxref("Performance.setResourceTimingBufferSize()")}}
- Sets the browser's resource timing buffer size to the specified number of "resource
" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects.
- {{domxref("Performance.toJSON()")}}
- Is a jsonizer returning a json object representing the Performance
object.
-
-
-Specifications
+{{APIRef("High Resolution Time")}}
-{{Specifications}}
+The **`Performance`** interface provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the [Performance Timeline API](/zh-TW/docs/Web/API/Performance_Timeline), the [Navigation Timing API](/zh-TW/docs/Web/API/Navigation_timing_API), the [User Timing API](/zh-TW/docs/Web/API/User_Timing_API), and the [Resource Timing API](/zh-TW/docs/Web/API/Resource_Timing_API).
+
+An object of this type can be obtained by calling the {{domxref("Window.performance")}} read-only attribute.
+
+> **備註:** This interface and its members are available in [Web Workers](/zh-TW/docs/Web/API/Web_Workers_API), except where indicated below. Also note that performance markers and measures are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.
+
+## Properties
+
+_The `Performance` interface doesn't inherit any properties._
+
+- {{deprecated_inline}} {{domxref("Performance.navigation")}} {{readonlyInline}}
+ - : A {{domxref("PerformanceNavigation")}} object that provides useful context about the operations included in the times listed in `timing`, including whether the page was a load or a refresh, how many redirections occurred, and so forth.
+- {{deprecated_inline}} {{domxref("Performance.timing")}} {{readonlyInline}}
+ - : A {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+- {{domxref("Performance.memory", "performance.memory")}} {{Non-standard_inline}}
+ - : A _non-standard_ extension added in Chrome, this property provides an object with basic memory usage information. _You **should not use** this non-standard API._
+- {{domxref("Performance.timeOrigin")}} {{readonlyInline}} {{Non-standard_inline}}
+ - : Returns the high resolution timestamp of the start time of the performance measurement.
+
+- ### Event handlers
-Browser compatibility
+ {{domxref("Performance.onresourcetimingbufferfull")}}
-
+ - : An {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
+## Methods
+
+_The `Performance` interface doesn't inherit any methods_.
+
+- {{domxref("Performance.clearMarks()")}}
+ - : Removes the given _mark_ from the browser's performance entry buffer.
+- {{domxref("Performance.clearMeasures()")}}
+ - : Removes the given _measure_ from the browser's performance entry buffer.
+- {{domxref("Performance.clearResourceTimings()")}}
+ - : Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "`resource`" from the browser's performance data buffer.
+- {{domxref("Performance.getEntries()")}}
+ - : Returns a list of {{domxref("PerformanceEntry")}} objects based on the given _filter_.
+- {{domxref("Performance.getEntriesByName()")}}
+ - : Returns a list of {{domxref("PerformanceEntry")}} objects based on the given _name_ and _entry type_.
+- {{domxref("Performance.getEntriesByType()")}}
+ - : Returns a list of {{domxref("PerformanceEntry")}} objects of the given _entry type_.
+- {{domxref("Performance.mark()")}}
+ - : Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's _performance entry buffer_ with the given name.
+- {{domxref("Performance.measure()")}}
+ - : Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the _start mark_ and _end mark_, respectively).
+- {{domxref("Performance.now()")}}
+ - : Returns a {{domxref("DOMHighResTimeStamp")}} representing the number of milliseconds elapsed since a reference instant.
+- {{domxref("Performance.setResourceTimingBufferSize()")}}
+ - : Sets the browser's resource timing buffer size to the specified number of "`resource`" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects.
+- {{domxref("Performance.toJSON()")}}
+ - : Is a jsonizer returning a json object representing the `Performance` object.
+
+## Specifications
+
+{{Specifications}}
+## Browser compatibility
-
{{Compat("api.Performance")}}
-
+{{Compat("api.Performance")}}
diff --git a/files/zh-tw/web/api/performance/timing/index.md b/files/zh-tw/web/api/performance/timing/index.md
index 12ad0f5440991e..ab9dff0b505143 100644
--- a/files/zh-tw/web/api/performance/timing/index.md
+++ b/files/zh-tw/web/api/performance/timing/index.md
@@ -13,26 +13,26 @@ tags:
translation_of: Web/API/Performance/timing
original_slug: Web/API/Performance.timing
---
-{{APIRef("Performance")}}
+{{APIRef("Performance")}}
-摘要
+## 摘要
-Performance
.timing
是唯讀的屬性,傳回的 {{domxref("PerformanceTiming")}} 物件當中包含了效能與時間延遲相關的資訊。
+**`Performance.timing`** 是唯讀的屬性,傳回的 {{domxref("PerformanceTiming")}} 物件當中包含了效能與時間延遲相關的資訊。
-語法
+## 語法
-timingInfo = performance .timing;
+```plain
+timingInfo = performance.timing;
+```
-規格
+## 規格
-因為 Navigation Timing 規範已被棄用,此特性不再有望成為標準。請使用 {{domxref("PerformanceNavigationTiming")}} 介面代替。
+因為 Navigation Timing 規範已被棄用,此特性不再有望成為標準。請使用 {{domxref("PerformanceNavigationTiming")}} 介面代替。
-瀏覽器支援狀況
+## 瀏覽器支援狀況
-{{Compat}}
+{{Compat}}
-參照
+## 參照
-
- 屬於 {{domxref("Performance")}} 界面的一部份
-
+- 屬於 {{domxref("Performance")}} 界面的一部份
diff --git a/files/zh-tw/web/api/permissions_api/index.md b/files/zh-tw/web/api/permissions_api/index.md
index 9ad422c907d0e0..a067194fcee7dd 100644
--- a/files/zh-tw/web/api/permissions_api/index.md
+++ b/files/zh-tw/web/api/permissions_api/index.md
@@ -4,35 +4,35 @@ slug: Web/API/Permissions_API
translation_of: Web/API/Permissions_API
original_slug: WebAPI/Permissions
---
-{{DefaultAPISidebar("Permissions API")}}
-
-摘要
-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
+{{DefaultAPISidebar("Permissions API")}}
+
+## 摘要
+
+Permissions API 可顯示 Apps 所要求的所有權限,以利使用者管理。Apps 可透過此 API 而讀取其他 Apps 的權限並進一步變更。
+
+透過 [`PermissionSettings`](/zh-TW/docs/DOM/PermissionSettings) 介面的 [`navigator.mozPermissionSettings`](/zh-TW/docs/DOM/window.navigator.mozPermissionSettings) 屬性,即可存取 Permission Manager。
+
+## 已安裝 Apps 的權限
+
+所有 Apps 均需透過自己的 manifest 檔案而要求權限。Apps 每次所使用的 API,均以「請求顯性權限 (Explicit Permission)」的 API 為主,並提示使用者是否通過權限。如果使用者選擇「不要再提示」,大概也就不太可能改變決定了。API 則能提供介面,以利使用者管理已發出的權限。
+
+透過 [`PermissionSettings.get()`](/zh-TW/docs/DOM/PermissionSettings.get)、[`set()`](/zh-TW/docs/DOM/PermissionSettings.set)、[`isExplicit()`](/zh-TW/docs/DOM/PermissionSettings.isExplicit) 函式即可達到上述作業。
+
+### 讀取權限
+
+若要知道已發出權限的目前狀態,可使用 [`PermissionSettings.get()`](/zh-TW/docs/DOM/PermissionSettings.get) 函式。此函式可回傳字串,以顯示特定 Apps 權限的目前狀態。可能的數值有:
+
+- `allow`
+ - : 已通過該權限,且不需使用者的進一步互動。
+- `denied`
+ - : 已否決該權限;可能是系統或使用者所否決。
+- `prompt`
+ - : 代表該權限將以明顯的提示方法,詢問使用者是否給予權限。
+- `unknown`
+ - : 代表該 Apps 並未詢問此權限,也不會提示使用者是否給予權限。
+
+```js
+// Let's check all installed apps
var apps = navigator.mozApps.mgmt.getAll();
apps.onsuccess = function () {
@@ -50,14 +50,16 @@ apps.onsuccess = function () {
}
});
}
+```
+
+### 設定權限
+
+只要使用 [`PermissionSettings.set()`](/zh-TW/docs/DOM/PermissionSettings.set) 函式即可設定權限。可能的數值均與 [`get`](/zh-TW/docs/DOM/PermissionSettings.get) 函式所存取的相同。
-
-設定權限
-只要使用 PermissionSettings.set()
函式即可設定權限。可能的數值均與 get
函式所存取的相同。
-
-// Let's check all installed apps
+> **備註:** 根據 Apps 權限的不同,某些可能為隱性 (Implicit) 權限。若因為某種理由,Apps 嘗試將權限變更為隱性權限,就會產生錯誤。為了避免這種錯誤,可透過 [`PermissionSettings.isExplicit()`](/zh-TW/docs/DOM/PermissionSettings.isExplicit) 函式而檢查是否為顯性權限。
+
+```js
+// Let's check all installed apps
var apps = navigator.mozApps.mgmt.getAll();
apps.onsuccess = function () {
@@ -75,11 +77,14 @@ apps.onsuccess = function () {
}
}
});
-}
-規格
-不屬於任何規格。
-另可參閱
-
- {{domxref("window.navigator.mozPermissionSettings","navigator.mozPermissionSettings")}}
- {{domxref("PermissionSettings")}}
-
+}
+```
+
+## 規格
+
+不屬於任何規格。
+
+## 另可參閱
+
+- {{domxref("window.navigator.mozPermissionSettings","navigator.mozPermissionSettings")}}
+- {{domxref("PermissionSettings")}}
diff --git a/files/zh-tw/web/api/pointer_lock_api/index.md b/files/zh-tw/web/api/pointer_lock_api/index.md
index 331e2909a9615c..4f5d1f31db4bf4 100644
--- a/files/zh-tw/web/api/pointer_lock_api/index.md
+++ b/files/zh-tw/web/api/pointer_lock_api/index.md
@@ -3,34 +3,33 @@ title: Pointer Lock API
slug: Web/API/Pointer_Lock_API
translation_of: Web/API/Pointer_Lock_API
---
-{{ SeeCompatTable() }}
+{{ SeeCompatTable() }}
-Pointer lock (之前稱為 Mouse lock) 提供「隨時間經過所產生的滑鼠位移資訊 (即 deltas)」的輸入方法,而不只是滑鼠游標的絕對位置而已。此函式可存取基本的滑鼠位移、將滑鼠事件的目標鎖定至單一元素、讓滑鼠單一方向的位移距離不再受限、將游標移除到視點之外。
+**Pointer lock** (之前稱為 Mouse lock) 提供「隨時間經過所產生的滑鼠位移資訊 (即 deltas)」的輸入方法,而不只是滑鼠游標的絕對位置而已。此函式可存取基本的滑鼠位移、將滑鼠事件的目標鎖定至單一元素、讓滑鼠單一方向的位移距離不再受限、將游標移除到視點之外。
-若 App 需要大量的滑鼠輸入以控制位移、旋轉物件、更改輸入項,那此 API 就特別有用。另對特別注重視覺效果的 App 尤其必要,如第一人稱視角、3D 視圖、模型建構等。
+若 App 需要大量的滑鼠輸入以控制位移、旋轉物件、更改輸入項,那此 API 就特別有用。另對特別注重視覺效果的 App 尤其必要,如第一人稱視角、3D 視圖、模型建構等。
-舉例來說,你可讓消費者不需點擊任何按鈕,只要透過滑鼠即可控制視角。而按鈕可用於其他動作。對於查看地圖、衛星圖像、第一人稱場景類 (如遊戲或虛擬實境影片) 的 App 來說,這種滑鼠輸入方式特別方便易用。
+舉例來說,你可讓消費者不需點擊任何按鈕,只要透過滑鼠即可控制視角。而按鈕可用於其他動作。對於查看地圖、衛星圖像、第一人稱場景類 (如遊戲或虛擬實境影片) 的 App 來說,這種滑鼠輸入方式特別方便易用。
-即使滑鼠游標移出瀏覽器或螢幕之外,Pointer lock 還是能讓你存取滑鼠事件。舉例來說,消費者還是可繼續移動滑鼠以旋轉或操作 3D 模型。若沒有 Pointer lock,則只要指標移出瀏覽器或螢幕之外,旋轉或操作隨即停止。遊戲玩家會特別喜歡此功能。他們現在可以隨便亂按按鈕並隨意滑動滑鼠;不再擔心滑鼠游標滑出遊戲區域而點到其他應用程式,結果退出遊戲發生慘案!
+即使滑鼠游標移出瀏覽器或螢幕之外,Pointer lock 還是能讓你存取滑鼠事件。舉例來說,消費者還是可繼續移動滑鼠以旋轉或操作 3D 模型。若沒有 Pointer lock,則只要指標移出瀏覽器或螢幕之外,旋轉或操作隨即停止。遊戲玩家會特別喜歡此功能。他們現在可以隨便亂按按鈕並隨意滑動滑鼠;不再擔心滑鼠游標滑出遊戲區域而點到其他應用程式,結果退出遊戲發生慘案!
-基本概念
+## 基本概念
-Pointer lock 與 mouse capture 相關。在拖曳滑鼠時,Mouse capture 可持續向目標元素傳遞事件,且只要放開滑鼠按鈕隨即跟著停止。Pointer lock 與 mouse capture 不同之處在於:
+Pointer lock 與 [mouse capture ](/en/DOM/element.setCapture)相關。在拖曳滑鼠時,Mouse capture 可持續向目標元素傳遞事件,且只要放開滑鼠按鈕隨即跟著停止。Pointer lock 與 mouse capture 不同之處在於:
-
- Pointer lock 屬持久性。除非發生顯式 (Explicit) API 呼叫,或使用者做出特定的釋放手勢,否則 Pointer lock 將不會釋放滑鼠。
- Pointer lock 不侷限於螢幕或瀏覽器的範圍。
- 不論滑鼠按鈕狀態為何,Pointer lock 將持續送出事件。
- Pointer lock 會隱藏游標。
-
+- Pointer lock 屬持久性。除非發生顯式 (Explicit) API 呼叫,或使用者做出特定的釋放手勢,否則 Pointer lock 將不會釋放滑鼠。
+- Pointer lock 不侷限於螢幕或瀏覽器的範圍。
+- 不論滑鼠按鈕狀態為何,Pointer lock 將持續送出事件。
+- Pointer lock 會隱藏游標。
-範例
+## 範例
-下列範例可讓你設定自己網頁上的 Pointer lock。
+下列範例可讓你設定自己網頁上的 Pointer lock。
-<button onclick="lockPointer();">Lock it!</button>
-<div id="pointer-lock-element"></div>
-<script>
+```js
+Lock it!
+
+
+```
-函式/屬性概述
+## 函式/屬性概述
-Pointer lock API 與 Fullscreen API 類似,可添增 requestPointerLock 新函式 (目前尚未標準化) 而擴充 DOM 元素。可為下列:
+Pointer lock API 與 Fullscreen API 類似,可添增 [requestPointerLock](/zh-TW/docs/Web/API/Element.requestPointerLock) 新函式 (目前尚未標準化) 而擴充 DOM 元素。可為下列:
-element.webkitRequestPointerLock(); // Chrome
+```js
+element.webkitRequestPointerLock(); // Chrome
element.mozRequestPointerLock(); // Firefox
-element.requestPointerLock(); // Standard
+element.requestPointerLock(); // Standard
+```
-目前在建置 requestPointerLock 時,還是必須緊密結合 requestFullScreen 與 Fullscreen API。在指標鎖定某一元素之前,必須先進入全螢幕模式。如同上方的 Demo,指標鎖定屬於非同步程序,並透過 pointerlockchange 與 pointerlockerror 事件,指出該請求是否成功。此與 Fullscreen API 的運作方式相同 (使用其 requestFullScreen 函式,另搭配 fullscreenchange 與 fullscreenerror 事件)。
+目前在建置 [requestPointerLock](/zh-TW/docs/Web/API/Element.requestPointerLock) 時,還是必須緊密結合 [requestFullScreen](/zh-TW/docs/Web/API/Element.requestFullScreen) 與 Fullscreen API。在指標鎖定某一元素之前,必須先進入全螢幕模式。如同上方的 Demo,指標鎖定屬於非同步程序,並透過 [pointerlockchange](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockchange) 與 [pointerlockerror](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockerror) 事件,指出該請求是否成功。此與 Fullscreen API 的運作方式相同 (使用其 [requestFullScreen](/zh-TW/docs/Web/API/Element.requestFullScreen) 函式,另搭配 [fullscreenchange](/zh-TW/docs/Web/API/GlobalEventHandlers.fullscreenchange) 與 [fullscreenerror](/zh-TW/docs/Web/API/GlobalEventHandlers.fullscreenerror) 事件)。
-Pointer lock API 另擴充了 and <table>) and provides functionality global to the document (suc">Document 介面,同時添增了新的屬性與函式。如果目前有鎖定的元素,則新的屬性可存取該所訂元素,並命名為 pointerLockElement (目前尚未標準化)。 and <table>) and provides functionality global to the document (suc">Document 上的新函式則為 exitPointerLock ;顧名思義,此函式可退出 Pointer lock。
+Pointer lock API 另擴充了 [and \ ) and provides functionality global to the document (suc">Document](/zh-TW/docs/Web/API/Document) 介面,同時添增了新的屬性與函式。如果目前有鎖定的元素,則新的屬性可存取該所訂元素,並命名為 [pointerLockElement](/zh-TW/docs/Web/API/Document.pointerLockElement) (目前尚未標準化)。[ and \) and provides functionality global to the document (suc">Document](/zh-TW/docs/Web/API/Document) 上的新函式則為 [exitPointerLock](/zh-TW/docs/Web/API/Document.exitPointerLock);顧名思義,此函式可退出 Pointer lock。
-pointerLockElement 屬性可確定指標目前是否鎖定了任何元素 (例如進行 Boolean 檢查)。若確實有鎖定的元素,則可取得參考。以下為此二種用法的範例:
+[pointerLockElement](/zh-TW/docs/Web/API/Document.pointerLockElement) 屬性可確定指標目前是否鎖定了任何元素 (例如進行 Boolean 檢查)。若確實有鎖定的元素,則可取得參考。以下為此二種用法的範例:
-document.pointerLockElement = document.pointerLockElement ||
+```js
+document.pointerLockElement = document.pointerLockElement ||
document.mozPointerLockElement ||
document.webkitPointerLockElement;
@@ -130,11 +132,12 @@ if (!!document.pointerLockElement) {
if (document.pointerLockElement === someElement) {
// someElement is currently pointer locked
}
-
+```
-Document.exitPointerLock 函式則用以退出 Pointer lock。且和 requestPointerLock 一樣,Document.exitPointerLock 是使用 pointerlockchange 與 pointerlockerror 事件,以非同步方式作業:
+[Document.exitPointerLock](/zh-TW/docs/Web/API/Document.exitPointerLock) 函式則用以退出 Pointer lock。且和 [requestPointerLock](/zh-TW/docs/Web/API/Element.requestPointerLock) 一樣,[Document.exitPointerLock](/zh-TW/docs/Web/API/Document.exitPointerLock) 是使用 [pointerlockchange](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockchange) 與 [pointerlockerror](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockerror) 事件,以非同步方式作業:
-document.exitPointerLock = document.exitPointerLock ||
+```js
+document.exitPointerLock = document.exitPointerLock ||
document.mozExitPointerLock ||
document.webkitExitPointerLock;
@@ -156,59 +159,59 @@ document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
// Attempt to unlock
document.exitPointerLock();
-
+```
-pointerlockchange 事件
+## pointerlockchange 事件
-若 Pointer lock 狀態改變,如呼叫 requestPointerLock 、exitPointerLock ,或使用者按下 ESC 鍵等。則 pointerlockchange 事件隨即傳送至 document
。此簡單事件不包含額外資料。
+若 Pointer lock 狀態改變,如呼叫 [requestPointerLock](/zh-TW/docs/Web/API/Element.requestPointerLock)、[exitPointerLock](/zh-TW/docs/Web/API/Document.exitPointerLock),或使用者按下 ESC 鍵等。則 [pointerlockchange](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockchange) 事件隨即傳送至 `document`。此簡單事件不包含額外資料。
-此事件目前在 Firefox 中的前綴為 mozpointerlockchange
;在 Chrome 中的前綴為 webkitpointerlockchange
。
+> **備註:** 此事件目前在 Firefox 中的前綴為 `mozpointerlockchange`;在 Chrome 中的前綴為 `webkitpointerlockchange`。
-pointerlockerror 事件
+## pointerlockerror 事件
-當呼叫 requestPointerLock 或 exitPointerLock 而發生錯誤時,隨即傳送 pointerlockerror 事件至 document
。此簡單事件不包含額外資料。
+當呼叫 [requestPointerLock](/zh-TW/docs/Web/API/Element.requestPointerLock) 或 [exitPointerLock](/zh-TW/docs/Web/API/Document.exitPointerLock) 而發生錯誤時,隨即傳送 [pointerlockerror](/zh-TW/docs/Web/API/GlobalEventHandlers.pointerlockerror) 事件至 `document`。此簡單事件不包含額外資料。
-此事件在 Firefox 中的前綴為 mozpointerlockerror
;在 Chrome 中的前綴為 webkitpointerlockerror
。
+> **備註:** 此事件在 Firefox 中的前綴為 `mozpointerlockerror`;在 Chrome 中的前綴為 `webkitpointerlockerror`。
-擴充至滑鼠事件
+## 擴充至滑鼠事件
-Pointer lock API 可透過位移屬性而擴充標準的 MouseEvent 介面。
+Pointer lock API 可透過位移屬性而擴充標準的 [MouseEvent](/zh-TW/docs/Web/API/MouseEvent) 介面。
-partial interface MouseEvent {
- readonly attribute long movementX ;
- readonly attribute long movementY ;
-};
+```plain
+partial interface MouseEvent {
+ readonly attribute long movementX;
+ readonly attribute long movementY;
+};
+```
-位移屬性目前在 Firefox 中的前綴為 .mozMovementX
與 .mozMovementY
;在 Chrome 中的前綴為.webkitMovementX
與 .webkitMovementY
。
+> **備註:** 位移屬性目前在 Firefox 中的前綴為 `.mozMovementX` 與 `.mozMovementY`;在 Chrome 中的前綴為`.webkitMovementX` 與 `.webkitMovementY`。
-滑鼠事件的二個新參數 (即 movementX 與 movementY ) 將提供滑鼠位置的變化情形。此二項參數的值,等於 MouseEvent 屬性值 (即 screenX 與 screenY ) 之間的變化;而 MouseEvent 屬性另儲存於二項連續的 mousemove 事件 (即 eNow 與 ePrevious) 之內。換句話說,Pointer lock 參數 movementX = eNow.screenX - ePrevious.screenX
。
+滑鼠事件的二個新參數 (即 [movementX](/zh-TW/docs/Web/API/MouseEvent.movementX) 與 [movementY](/zh-TW/docs/Web/API/MouseEvent.movementY)) 將提供滑鼠位置的變化情形。此二項參數的值,等於 [MouseEvent](/zh-TW/docs/Web/API/MouseEvent) 屬性值 (即 [screenX](/zh-TW/docs/Web/API/MouseEvent.screenX) 與 [screenY](/zh-TW/docs/Web/API/MouseEvent.screenY)) 之間的變化;而 [MouseEvent](/zh-TW/docs/Web/API/MouseEvent) 屬性另儲存於二項連續的 [mousemove](/zh-TW/docs/Web/API/GlobalEventHandlers.mousemove) 事件 (即 eNow 與 ePrevious) 之內。換句話說,Pointer lock 參數 `movementX = eNow.screenX - ePrevious.screenX`。
-鎖定狀態
+### 鎖定狀態
-在啟動 Pointer lock 之後,標準的 MouseEvent 屬性 clientX 、clientY 、screenX 、screenY 均維持不變,如同滑鼠沒有移動。movementX 與 movementY 屬性將持續提供滑鼠的位置變化。如果滑鼠朝單一方向持續移動,movementX 與 movementY 的值也就不受限。此時「滑鼠游標」的概念不存在,游標無法移出視窗之外,也不會受限於螢幕邊界。
+在啟動 Pointer lock 之後,標準的 [MouseEvent](/zh-TW/docs/Web/API/MouseEvent) 屬性 [clientX](/zh-TW/docs/Web/API/MouseEvent.clientX)、[clientY](/zh-TW/docs/Web/API/MouseEvent.clientY)、[screenX](/zh-TW/docs/Web/API/MouseEvent.screenX)、[screenY](/zh-TW/docs/Web/API/MouseEvent.screenY) 均維持不變,如同滑鼠沒有移動。[movementX](/zh-TW/docs/Web/API/MouseEvent.movementX) 與 [movementY](/zh-TW/docs/Web/API/MouseEvent.movementY) 屬性將持續提供滑鼠的位置變化。如果滑鼠朝單一方向持續移動,[movementX](/zh-TW/docs/Web/API/MouseEvent.movementX) 與 [movementY](/zh-TW/docs/Web/API/MouseEvent.movementY) 的值也就不受限。此時「滑鼠游標」的概念不存在,游標無法移出視窗之外,也不會受限於螢幕邊界。
-未鎖定狀態
+### 未鎖定狀態
-無論滑鼠的鎖定狀態為何,movementX 與 movementY 參數均保持有效;另為了方便起見,甚至在未鎖定狀態下仍可保持有效。
+無論滑鼠的鎖定狀態為何,[movementX](/zh-TW/docs/Web/API/MouseEvent.movementX) 與 [movementY](/zh-TW/docs/Web/API/MouseEvent.movementY) 參數均保持有效;另為了方便起見,甚至在未鎖定狀態下仍可保持有效。
-在解鎖滑鼠之後,系統游標可退出並重新進入瀏覽器視窗,且 movementX 與 movementY 此時可能設定為零。
+在解鎖滑鼠之後,系統游標可退出並重新進入瀏覽器視窗,且 [movementX](/zh-TW/docs/Web/API/MouseEvent.movementX) 與 [movementY](/zh-TW/docs/Web/API/MouseEvent.movementY) 此時可能設定為零。
-iframe 限制
+## iframe 限制
-Pointer lock 一次僅能鎖定一組 iframe。在鎖定一組 iframe 之後,就無法鎖定另一組 iframe 並轉移目標至該 iframe 之上;Pointer lock 將發生錯誤。為擺脫此限制,必須先將鎖定的 iframe 解鎖,再鎖定另一組 iframe。
+Pointer lock 一次僅能鎖定一組 iframe。在鎖定一組 iframe 之後,就無法鎖定另一組 iframe 並轉移目標至該 iframe 之上;Pointer lock 將發生錯誤。為擺脫此限制,必須先將鎖定的 iframe 解鎖,再鎖定另一組 iframe。
-由於 iframes 是根據預設值運作,因此預設為「沙箱式 (sandboxed)」的 iframes 將阻擋 Pointer lock。為擺脫此限制,Chrome 應該很快就會推出 <iframe sandbox="allow-pointer-lock">
的「屬性/值」整合形式。
+由於 iframes 是根據預設值運作,因此預設為「沙箱式 (sandboxed)」的 iframes 將阻擋 Pointer lock。為擺脫此限制,Chrome 應該很快就會推出 `