From 43a5cac2eff22c21071800e13bef12af9d3a37d0 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 13:12:08 +0100 Subject: unslug zh-tw: move --- files/zh-tw/learn/css/howto/css_faq/index.html | 165 ++++++ .../forms/how_to_structure_a_web_form/index.html | 315 ++++++++++++ files/zh-tw/learn/forms/index.html | 359 +++++++++++++ files/zh-tw/learn/how_to_contribute/index.html | 81 --- .../forms/how_to_structure_an_html_form/index.html | 315 ------------ files/zh-tw/learn/html/forms/index.html | 359 ------------- .../index.html" | 502 ------------------ .../images_in_html/index.html | 502 ++++++++++++++++++ .../other_embedding_technologies/index.html | 386 ++++++++++++++ .../index.html" | 386 -------------- files/zh-tw/learn/html/tables/basics/index.html | 568 +++++++++++++++++++++ .../tables/\345\237\272\347\244\216/index.html" | 568 --------------------- .../javascript/building_blocks/events/index.html | 85 +++ .../zh-tw/learn/performance/multimedia/index.html | 130 +++++ .../index.html" | 130 ----- .../first_steps/introduction/index.html | 225 ++++++++ .../\344\273\213\347\264\271/index.html" | 225 -------- 17 files changed, 2735 insertions(+), 2566 deletions(-) create mode 100644 files/zh-tw/learn/css/howto/css_faq/index.html create mode 100644 files/zh-tw/learn/forms/how_to_structure_a_web_form/index.html create mode 100644 files/zh-tw/learn/forms/index.html delete mode 100644 files/zh-tw/learn/how_to_contribute/index.html delete mode 100644 files/zh-tw/learn/html/forms/how_to_structure_an_html_form/index.html delete mode 100644 files/zh-tw/learn/html/forms/index.html delete mode 100644 "files/zh-tw/learn/html/multimedia_and_embedding/html\344\270\255\347\232\204\345\234\226\347\211\207/index.html" create mode 100644 files/zh-tw/learn/html/multimedia_and_embedding/images_in_html/index.html create mode 100644 files/zh-tw/learn/html/multimedia_and_embedding/other_embedding_technologies/index.html delete mode 100644 "files/zh-tw/learn/html/multimedia_and_embedding/\345\205\266\344\273\226_\345\265\214\345\205\245_\346\212\200\350\241\223/index.html" create mode 100644 files/zh-tw/learn/html/tables/basics/index.html delete mode 100644 "files/zh-tw/learn/html/tables/\345\237\272\347\244\216/index.html" create mode 100644 files/zh-tw/learn/javascript/building_blocks/events/index.html create mode 100644 files/zh-tw/learn/performance/multimedia/index.html delete mode 100644 "files/zh-tw/learn/performance/\345\244\232\345\252\222\351\253\224/index.html" create mode 100644 files/zh-tw/learn/server-side/first_steps/introduction/index.html delete mode 100644 "files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" (limited to 'files/zh-tw/learn') diff --git a/files/zh-tw/learn/css/howto/css_faq/index.html b/files/zh-tw/learn/css/howto/css_faq/index.html new file mode 100644 index 0000000000..b824c671c4 --- /dev/null +++ b/files/zh-tw/learn/css/howto/css_faq/index.html @@ -0,0 +1,165 @@ +--- +title: CSS 一般問題 +slug: Web/CSS/Common_CSS_Questions +tags: + - CSS + - 待審閱技術 + - 待審閱文字 + - 所有類別 +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

+

+

我的 CSS 合乎規格,但繪出的版面有誤

+

如果想讓大部分的瀏覽器都能正確繪製標準 HTML/CSS 頁面,便須於 HTML 檔案中放上完整的正確 DOCTYPE。 +

新近瀏覽器都有兩種佈局模式: +

+ +

以 Gecko 為核心的瀏覽器都有第三種近乎標準模式,其中只有一些些不合規範的地方。 +

如果你宣告的 DTD 不合標準或過期了,那麼瀏覽器就會進入 Quirks 模式。 +

以下是常用的 DTD 列表,可以讓瀏覽器進入標準或近乎標準模式。 +

+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+

idclass 之間的差別

+

HTML 元素都可有 idclass 屬性。id 屬性是讓你為元素命名的,整個頁面中的元素名稱也不應有重複;class 屬性則可將元素歸為某特定類別,通常也會有很多元素屬於同一種類別 (意即 class 屬性值相同。) CSS 可以讓你以 idclass 來決定某元素的樣式。 +

如果你想指定某特定單一元素的樣式,則應使用 id。 +

+
+

若有很多個元素皆有相同樣式,則可使用 class。 +

這方面的資訊亦可參考 CSS 選取符。 +

+
+

恢復某特性的預設值

+

CSS2 並不提供任何指定某特性預設值的方法,所以要恢復某特性預設值的唯一方法就是重新指定此值。此外你自己得知道預設值是什麼,因為 CSS 也沒有所謂 default 的關鍵字。 +

所以,以選取符撰寫樣式時須特別注意 (例如以標籤名稱 p 作為選取符),或許可以用更明確的選取符 (例如 ID 或 class)。以標籤名稱作選取符茲事體大,一旦使用便將影響整個網頁,而且沒有自動恢復預設值的方法。 +

此外,由於 CSS 具串聯特性,指定選取符時通常越明確越好,以免把不相干的元素都牽扯進來。 +

+

相依樣式

+

CSS 並不支援「以另一個樣式規則為基準」的樣式設定法。 (參考 Eric Meyer 所寫、關於 CSS 工作小組的說明。) 不過,你可以為某單一元素套上多重樣式,製作出類似效果。 +

+

套用多重類別

+

你可以在 HTML 元素的 class 屬性裡以空白字元分隔填上多個樣式類別名稱,便能同時套用多重類別。 +

+
<style type="text/css">
+.firstclass { background: black; color: white; }
+.secondclass { font-weight: bold; }
+</style>
+
+<div class="firstclass secondclass">
+... content ...
+... content ...
+... content ...
+</div>
+
+

若是這些規則中設定了同一種特性值,則會依序以明確性(specificity)、定義位置先後決定顯示方式,與class 屬性中的次序無關。 +

+

無用樣式

+

即使樣式規則已經正確設定完畢,還是可能為瀏覽器所忽略,此時通常是經過語法及優先權法則判斷後的正常現象。 +

以下是導致樣式被略過的常見情形: +

+ +

你可以使用 DOM 觀察器CSS Style Rules 來檢查上述問題。 +

HTML 元素層次問題 +

此時 CSS 樣式套用與否與元素的層次大有相關,請留意:套用到子元素的樣式必定會蓋過母元素的樣式,跟明確性或 CSS 規則的優先權無關。 +

+
#section { font-weight: bold; }
+.redtext { font-weight: normal; color: red; }
+
+<div id="section">
+   粗體、
+   <span class="redtext">正常紅字、</span>
+   又見粗體
+</div>
+
+

如果你的 HTML 層級錯綜複雜,發生規則意外被忽略的情形時,請檢查元素層級問題。可能有某個子元素套上了不該用的樣式。 +

樣式規則重新定義 +

在 CSS 樣式表中,先後次序非常重要。如果你定義了某規則後又重新定義一次,則晚定義的才算數。 +

+
#section { font-weight: bold; }
+.redtext { color: red; }
+/* 其他規則 */
+/* 其他規則 */
+/* 其他規則 */
+.redtext { color: green; }
+
+<div id="section">
+粗體、
+<span class="redtext">正常紅字?</span>
+又見粗體
+</div>
+
+

為避免此類錯誤發生,每個特定選取符請僅定義一次樣式,集中特性一次定義也便於管理些。 +


+特性的簡寫法 +

使用簡寫法來定義樣式簡明扼要,是個不錯的方法。你也可以用簡寫法設定某組特性中的部分特性值,但須留意其他沒寫到的部分會自動採用預設值。這表示之前的規則中為某單一特性定義的值可能失效。 +

+
#section { font-size: 12px; font-family: Verdana; font-weight: bold; }
+.redtext { font: 14px Arial; color: red; }
+
+<div id="section">
+   採用 Verdana 粗體的 12px 字樣;
+   <span class="redtext">採用 Arial 正常字體的 14px 紅字;</span>
+   還是採用 Verdana 粗體的 12px 字樣。
+</div>
+
+

前一個例子中,套用到不同元素範圍的同族特性是問題所在,但就算特性都寫在同一條規則裡也可能出問題,因為順序真的很重要。 +

+
#section {
+   font-weight: bold;
+   font: 12px Verdana;  /* 有了這行,font-weight 又回到預設的 normal 了 */
+}
+
+


+使用 * 選取符 +

* 選取符表示任何元素皆符合,但使用上應多加小心。 +

+
body * { font-weight: normal; }
+#section { font: 12px Verdana; }
+.boldtext { font-weight: bold; }
+.redtext { color: red; }
+
+<div id="section">
+   正常、
+   <span class="boldtext">
+      <span class="redtext">正常紅字、</span>
+   </span>
+   又見正常。
+</div>
+
+

在此例中,選取符為 body * 的規則會套用到所有 body 內的元素,也包括 redtext,所以原先套用到 boldtextfont-weight: bold; 就被覆蓋為 font-weight: normal; 了。 +


+CSS 明確性 +

如果某元素會套用好幾條規則,則相衝突的特性就要靠規則的明確性來分高下。行內樣式(放在 HTML 各標籤的 style 屬性中)優先權最高,其次是以 id 做選取符的規則,再其次是以 class 套用的類別,最後則是單純以元素名稱當選取符的規則。 +

+
div { color: black; }
+#orange { color: orange; }
+.green { color: green; }
+
+<div id="orange" class="green" style="color: red;">是紅的!</div>
+
+

如果樣式規則的選取符分成好幾段,計算方式就更為複雜一些。需要瞭解完整資訊者,請參考 CSS 2.1 規格書的 6.4.3 一節。 +

+

-moz-* 特性是什麼玩意?

+

請見 Mozilla 擴充的 CSS。由於這些擴充規格不是 W3C 標準的一部分,因此並不建議使用。 +

+
+
+{{ languages( { "en": "en/Common_CSS_Questions", "pl": "pl/Cz\u0119ste_pytania_o_CSS" } ) }} diff --git a/files/zh-tw/learn/forms/how_to_structure_a_web_form/index.html b/files/zh-tw/learn/forms/how_to_structure_a_web_form/index.html new file mode 100644 index 0000000000..b403666795 --- /dev/null +++ b/files/zh-tw/learn/forms/how_to_structure_a_web_form/index.html @@ -0,0 +1,315 @@ +--- +title: 如何建構 HTML 表單 +slug: Learn/HTML/Forms/How_to_structure_an_HTML_form +translation_of: Learn/Forms/How_to_structure_a_web_form +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}
+ +

有了基礎後,我們就能探討表單元素,所提供的結構與文意之詳細資訊;還有各表單部份的相異之處。

+ + + + + + + + + + + + +
先決條件:對電腦還有 HTML 有基本理解。
目標:理解如何構建 HTML 表單並給予無障礙的語意化。
+ +

表單表單的彈性化令其成為 HTML 最複雜的結構之一。你能使用專用的表單元素和屬性,來構建任何類型的基本表單。使用正確的 HTML 表單結構能讓確保表單可用、且無障礙

+ +

<form> 元素

+ +

{{HTMLElement("form")}} 元素會形式上的定義表單和決定行為屬性。每次建立 HTML 表單時,都必須使用 form 元素;並將所有內容嵌進去。大多數的輔助技術與瀏覽器套件,都能抓到 {{HTMLElement("form")}} 元素,並實做特殊的 hook,使其更易於使用。

+ +

我們之前就講過這件事了。

+ +
注意:絕對不能在表單裡面再嵌入表單。這會讓表單行為變得難以理解,所以是一個壞主意。
+ +

你可以從表單外面控制 {{HTMLElement("form")}} 。這麼做的話,除非使用 form 將其與表單關聯,否則該操作預設上和任何表單無關。引入此功能是為了可以在即使該操作未嵌在表單中,其依舊能顯式地將操作與表單綁定。

+ +

接下來就開始探討表單裡面可能會嵌入什麼吧。

+ +

<fieldset> and <legend> 元素

+ +

{{HTMLElement("fieldset")}} 元素能方便地建立用途相近、樣式及語意化都很方便的小部件組(groups of widgets)。你可以透過添加 {{HTMLElement("legend")}} 來給 {{HTMLElement("fieldset")}} 的內部開頭添加標籤。{{HTMLElement("legend")}} 的文字內容能描述 {{HTMLElement("legend")}} 目的。

+ +

多數輔助科技會在 {{HTMLElement("legend")}} 元素被 {{HTMLElement("fieldset")}} 包住時偵測並使用它。比如說 JawsNVDA 之類的螢幕報讀器就會在讀到每個控件的標籤前,讀出 legend 的內容。

+ +

下面就有一個示例:

+ +
<form>
+  <fieldset>
+    <legend>Fruit juice size</legend>
+    <p>
+      <input type="radio" name="size" id="size_1" value="small">
+      <label for="size_1">Small</label>
+    </p>
+    <p>
+      <input type="radio" name="size" id="size_2" value="medium">
+      <label for="size_2">Medium</label>
+    </p>
+    <p>
+      <input type="radio" name="size" id="size_3" value="large">
+      <label for="size_3">Large</label>
+    </p>
+  </fieldset>
+</form>
+ +
+

:你可以在fieldset-legend.html 觀察範例(或著觀察這個動態互動)。

+
+ +

在閱讀表單時,螢幕報讀器會針對第一個小部件組,說出「Fruit juice size small」、接著針對第二個小部件組,說出「Fruit juice size medium」、第三個則是「Fruit juice size large」。

+ +

這個示例的是最重要的用法之一:每次有一組 radio 按鈕時,就該在裡面放一個 {{HTMLElement("fieldset")}} 元素。{{HTMLElement("fieldset")}} 也能用在表單的其他地方。理想上,要是表單一長,就要把他放到其他頁面。但如果做不到這點,那將不同的相關部分,放在不同的 fieldsets 之中,也可以提高可用性。

+ +

由於 {{HTMLElement("fieldset")}} 對輔助技術的影響,這個元素是建立無障礙表單的基石,但請注意不要濫用這個元素。可以的話,聽聽螢幕報讀是怎麼講的。如果踢起來怪怪的,那就試著改進表單。

+ +

<label> 元素

+ +

正如上篇文章中所見,{{HTMLElement("label")}} 元素是定義 HTML 表單控件的正式方法。如果要構建無障礙的表單,這是最重要的元素:正確實做後,螢幕閱讀器會說出表單元素標籤、以及相關說明,同時也對有視力的用戶很有用。以這個例子為例,我們在上一篇文章中看過:

+ +
<label for="name">Name:</label> <input type="text" id="name" name="user_name">
+ +

<label> 元素透過 for 屬性與 <input> 元素的 id 屬性正確連結後,螢幕閱讀器就會讀出「Name, edit text」這樣的文字。

+ +

還有另一種控制標籤與表單控件關聯的方法:那就是把表單控件嵌在 <label> 元素裡面,以便隱式關聯。

+ +
<label for="name">
+  Name: <input type="text" id="name" name="user_name">
+</label>
+ +

但即使在這種情況下,最好還是設置 for 屬性,以確保所有輔具都能理解標籤和控件之間的關係。

+ +

如果沒有標籤、或著說表單控件沒有被顯式或隱式關聯,螢幕閱讀器會讀出沒啥幫助的「Edit text blank」。

+ +

標籤也能點喔!

+ +

使用標籤的另一個好處,就是能在點選該標籤後,啟動相對應的小部件。這種功能在控制文字輸入的時候會很好用:用戶點選標籤時就可以 focus 到 input 那邊。這對 button 與 checkbox 尤其有用:因為點選的區域可能很小,因此使它盡可能簡單地啟用,會是很有用的。

+ +

例如在下面的示例中,點選「I like cherry」標籤文字後會切換 taste_cherry checkbox 的點選狀態:

+ +
<form>
+  <p>
+    <input type="checkbox" id="taste_1" name="taste_cherry" value="cherry">
+    <label for="taste_1">I like cherry</label>
+  </p>
+  <p>
+    <input type="checkbox" id="taste_2" name="taste_banana" value="banana">
+    <label for="taste_2">I like banana</label>
+  </p>
+</form>
+ +
+

:你可以在 checkbox-label.html 觀察示例(這裡有展示版本!

+
+ +

多個標籤

+ +

嚴格來說,一個小部件組能放很多個標籤,但由於部分輔助科技處理上會有問題,所以這也不是個好點子。如果有多個標籤,請試著把巢狀各個小部件,並在裡面只安插一個 {{htmlelement("label")}} 元素。

+ +

來看看這個例子:

+ +
<p>Required fields are followed by <abbr title="required">*</abbr>.</p>
+
+<!-- So this: -->
+<div>
+  <label for="username">Name:</label>
+  <input id="username" type="text" name="username">
+  <label for="username"><abbr title="required" aria-label="required">*</abbr></label>
+</div>
+
+<!-- would be better done like this: -->
+<div>
+  <label for="username">
+    <span>Name:</span>
+    <input id="username" type="text" name="username">
+    <abbr title="required" aria-label="required">*</abbr>
+  </label>
+</div>
+
+<!-- But this is probably best: -->
+<div>
+  <label for="username">Name: <abbr title="required" aria-label="required">*</abbr></label>
+  <input id="username" type="text" name="username">
+</div>
+ +

{{EmbedLiveSample("Multiple_labels", 120, 120)}}

+ +

The paragraph at the top states a rule for required elements. The rule must be included before it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. While this helps inform users what an asterisk means, it can not be relied upon. A screen reader will speak an asterisk as "star" when encountered. When hovered by a sighted mouse user, "required" should appear, which is achieved by use of the title attribute. Titles being read aloud depend on the screen reader's settings, so it is more reliable to also include the aria-label attribute, which is always read by screen readers.

+ +

The above variants increase in effectiveness as you go through them:

+ + + +
+

Note: You might get slightly different results, depending on your screenreader. This was tested in VoiceOver (and NVDA behaves similarly). We'd love to hear about your experiences too.

+
+ +
+

Note: You can find this example on GitHub as required-labels.html (see it live also). don't test the example with 2 or 3 of the versions uncommented — screenreaders will definitely get confused if you have multiple labels AND multiple inputs with the same ID!

+
+ +

建立表單所常用的 HTML 結構

+ +

Beyond the structures specific to web forms, it's good to remember that form markup is just HTML. This means that you can use all the power of HTML to structure a web form.

+ +

As you can see in the examples, it's common practice to wrap a label and its widget with a {{HTMLElement("li")}} element within a {{HTMLElement("ul")}} or {{HTMLElement("ol")}} list. {{HTMLElement("p")}} and {{HTMLElement("div")}} elements are also commonly used. Lists are recommended for structuring multiple checkboxes or radio buttons.

+ +

In addition to the {{HTMLElement("fieldset")}} element, it's also common practice to use HTML titles (e.g. {{htmlelement("h1")}}, {{htmlelement("h2")}}) and sectioning (e.g. {{htmlelement("section")}}) to structure complex forms.

+ +

Above all, it is up to you to find a comfortable coding style that results in accessible, usable forms. Each separate section of functionality should be contained in a separate {{htmlelement("section")}} element, with {{htmlelement("fieldset")}} elements to contain radio buttons.

+ +

主動學習:建立表單結構

+ +

Let's put these ideas into practice and build a slightly more involved form — a payment form. This form will contain a number of control types that you may not yet understand. Don't worry about this for now; you'll find out how they work in the next article (Basic native form controls). For now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why.

+ +
    +
  1. To start with, make a local copy of our blank template file and the CSS for our payment form in a new directory on your computer.
  2. +
  3. Apply the CSS to the HTML by adding the following line inside the HTML {{htmlelement("head")}}: +
    <link href="payment-form.css" rel="stylesheet">
    +
  4. +
  5. Next, create your form by adding the outer {{htmlelement("form")}} element: +
    <form>
    +
    +</form>
    +
  6. +
  7. Inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: +
    <h1>Payment form</h1>
    +<p>Required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p>
    +
  8. +
  9. Next we'll add a larger section of code into the form, below our previous entry. Here you'll see that we are wrapping the contact information fields inside a distinct {{htmlelement("section")}} element. Moreover, we have a set of two radio buttons, each of which we are putting inside its own list ({{htmlelement("li")}}) element. We also have two standard text {{htmlelement("input")}}s and their associated {{htmlelement("label")}} elements, each contained inside a {{htmlelement("p")}}, and a password input for entering a password. Add this code to your form: +
    <section>
    +    <h2>Contact information</h2>
    +    <fieldset>
    +      <legend>Title</legend>
    +      <ul>
    +          <li>
    +            <label for="title_1">
    +              <input type="radio" id="title_1" name="title" value="K" >
    +              King
    +            </label>
    +          </li>
    +          <li>
    +            <label for="title_2">
    +              <input type="radio" id="title_2" name="title" value="Q">
    +              Queen
    +            </label>
    +          </li>
    +          <li>
    +            <label for="title_3">
    +              <input type="radio" id="title_3" name="title" value="J">
    +              Joker
    +            </label>
    +          </li>
    +      </ul>
    +    </fieldset>
    +    <p>
    +      <label for="name">
    +        <span>Name: </span>
    +        <strong><abbr title="required">*</abbr></strong>
    +      </label>
    +      <input type="text" id="name" name="username">
    +    </p>
    +    <p>
    +      <label for="mail">
    +        <span>E-mail: </span>
    +        <strong><abbr title="required">*</abbr></strong>
    +      </label>
    +      <input type="email" id="mail" name="usermail">
    +    </p>
    +    <p>
    +      <label for="pwd">
    +        <span>Password: </span>
    +        <strong><abbr title="required">*</abbr></strong>
    +      </label>
    +      <input type="password" id="pwd" name="password">
    +    </p>
    +</section>
    +
  10. +
  11. The second <section> of our form is the payment information. We have three distinct controls along with their labels, each contained inside a <p>. The first is a drop-down menu ({{htmlelement("select")}}) for selecting credit card type. The second is an <input> element of type tel, for entering a credit card number; while we could have used the number type, we don't want the number's spinner UI. The last one is an <input> element of type date, for entering the expiration date of the card; this one will come up with a date picker widget in supporting browsers, and fall back to a normal text input in non-supporting browsers. These newer input types are reintroduced in The HTML5 input types.
    +
    + Enter the following below the previous section: +
    <section>
    +    <h2>Payment information</h2>
    +    <p>
    +      <label for="card">
    +        <span>Card type:</span>
    +      </label>
    +      <select id="card" name="usercard">
    +        <option value="visa">Visa</option>
    +        <option value="mc">Mastercard</option>
    +        <option value="amex">American Express</option>
    +      </select>
    +    </p>
    +    <p>
    +      <label for="number">
    +        <span>Card number:</span>
    +        <strong><abbr title="required">*</abbr></strong>
    +      </label>
    +      <input type="tel" id="number" name="cardnumber">
    +    </p>
    +    <p>
    +      <label for="date">
    +        <span>Expiration date:</span>
    +        <strong><abbr title="required">*</abbr></strong>
    +        <em>formatted as mm/dd/yyyy</em>
    +      </label>
    +      <input type="date" id="date" name="expiration">
    +    </p>
    +</section>
    +
  12. +
  13. The last section we'll add is a lot simpler, containing only a {{htmlelement("button")}} of type submit, for submitting the form data. Add this to the bottom of your form now: +
    <p> <button type="submit">Validate the payment</button> </p>
    +
  14. +
+ +

You can see the finished form in action below (also find it on GitHub — see our payment-form.html source and running live):

+ +

{{EmbedLiveSample("A_payment_form","100%",620, "", "Learn/Forms/How_to_structure_a_web_form/Example")}}

+ +

結論

+ +

你現在擁有了正確建構 HTML 表單的所有知識。接下來將介紹本章介紹的許多功能。在下一篇文章中,將詳細探討如何使用各種不同類型的表單小部件,來收集用戶的訊息。

+ +

參見

+ + + +

{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}

+ +

在本模塊

+ + + +

Advanced Topics

+ + diff --git a/files/zh-tw/learn/forms/index.html b/files/zh-tw/learn/forms/index.html new file mode 100644 index 0000000000..589880794f --- /dev/null +++ b/files/zh-tw/learn/forms/index.html @@ -0,0 +1,359 @@ +--- +title: 網站表單-與數據合作 +slug: Learn/HTML/Forms +tags: + - Featured + - Forms + - Guide + - HTML + - NeedsTranslation + - TopicStub + - Web + - 待翻譯 +translation_of: Learn/Forms +--- +

這篇指南提供了一系列的文章,幫你掌握HTML表單的基本知識。對於與使用者互動,網站表單是一項十分有力的工具,最常使用於用戶數據蒐集,或控制使用者介面。但由於一些歷史與技術上的因素,並沒有顯著的方法發揮表單的潛力。在下面的指引中,我們將介紹網站表單所有基本面向,包括標記他們的HTML結構、設定控制器樣式、驗證數據及將數距提送至伺服器

+ +

參考文章列表

+ +
    +
  1. 我的第一個HTML表單
  2. +
  3. 如何構建 HTML 表單
  4. +
  5. 本機表單控件
  6. +
  7. CSS和HTML表單 +
      +
    1. 造型HTML表單
    2. +
    3. HTML表單高級造型
    4. +
    5. 表單控件屬性兼容表
    6. +
    +
  8. +
  9. 發送和檢索表單數據
  10. +
  11. 數據表單驗證
  12. +
  13. 如何創建自定義表單控件
  14. +
  15. 通過JavaScript發送形式 +
      +
    1. 使用FORMDATA 對象
    2. +
    +
  16. +
  17. 在傳統的瀏覽器的HTML表單
  18. +
+ +

HTML 文件

+ +

HTML 元素

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HTML 元素元素的 DOM interface說明
{{HTMLElement("button")}}{{domxref("HTMLButtonElement")}}按鈕元素表示一個可點擊的按鈕。
{{HTMLElement("datalist")}}{{domxref("HTMLDataListElement")}}數據列表元素包含了一組  {{ HTMLElement("option") }}  表示對其他表單元素的值可能的選擇要素。
{{HTMLElement("fieldset")}}{{domxref("HTMLFieldSetElement")}}字段集是用來在表單中的組數表單元素。
{{HTMLElement("form")}}{{domxref("HTMLFormElement")}}形式元素表示的文件的一部分,它包含使用戶能夠提交信息給web服務器的交互元件。
{{HTMLElement("input")}}{{domxref("HTMLInputElement")}}該  輸入元素用於創建表格的交互式控制。
{{HTMLElement("keygen")}}{{domxref("HTMLKeygenElement")}}所述凱基元素存在,以促進生成的密鑰材料,並提交了公開密鑰的作為HTML形式的一部分
{{HTMLElement("label")}}{{domxref("HTMLLabelElement")}}標籤元素代表一個項目在用戶界面的標題
{{HTMLElement("legend")}}{{domxref("HTMLLegendElement")}}傳說元素代表一個標題為其父 {{ HTMLElement("fieldset") }} 的內容。
{{HTMLElement("meter")}}{{domxref("HTMLMeterElement")}}所述元素表示一個已知的範圍內的任一標量值或分數值。
{{HTMLElement("optgroup")}}{{domxref("HTMLOptGroupElement")}}OPTGROUP元素創建一個 {{ HTMLElement("select") }}  元素中的一組選項。
{{HTMLElement("option")}}{{domxref("HTMLOptionElement")}}在HTML 選項元素用於創建表示  {{ HTMLElement("select") }} ,一個 {{ HTMLElement("optgroup") }}  {{ HTMLElement("datalist") }} 元素中的項目的控制。
{{HTMLElement("output")}}{{domxref("HTMLOutputElement")}}輸出元素表示一個計算的結果。
{{HTMLElement("progress")}}{{domxref("HTMLProgressElement")}}進展元素用於查看任務的完成進度。
{{HTMLElement("select")}}{{domxref("HTMLSelectElement")}}選擇元素代表呈現一個選項菜單的控制。
{{HTMLElement("textarea")}}{{domxref("HTMLTextAreaElement")}}textarea的元素代表多行純文本編輯控制。
+ +
+

注:所有的表單元素,因為所有的HTML元素,支持 {{domxref("HTMLElement")}} DOM接口。

+
+ +

HTML 屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性能使用該屬性的 HTML 元素說明
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}的類型列表服務器接受,通常是文件類型。
accept-charset{{ HTMLElement("form") }}支持的字符集列表。
action{{ HTMLElement("form") }}一個程序處理通過表單提交的信息的URI。
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}指示是否在這個表單控件可以在默認情況下有其值由瀏覽器自動完成。
autofocus{{ HTMLElement("button") }}、 {{ HTMLElement("input") }}、 {{ HTMLElement("keygen") }}、 {{ HTMLElement("select") }}、 {{ HTMLElement("textarea") }}該元素應該在頁面加載後自動聚焦。
challenge{{ HTMLElement("keygen") }}即隨著公共密鑰提交的挑戰字符串。
checked{{ HTMLElement("input") }}指示是否應將元素在頁面加載檢查。
cols{{ HTMLElement("textarea") }}限定在一個textarea的列數。
data{{ HTMLElement("object") }}指定的資源的URL。
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}
disabled{{ HTMLElement("button") }} 、{{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("optgroup") }} 、 {{ HTMLElement("option") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea")}}表明用戶是否可以與元件進行交互。
enctype{{ HTMLElement("form") }}定義當表單數據的內容類型的方法是POST。
for{{ HTMLElement("label") }}、 {{ HTMLElement("output") }}描述了屬於這一種元素。
form{{ HTMLElement("button") }} 、 {{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("label") }} 、 {{ HTMLElement("meter") }} 、 {{ HTMLElement("object") }} 、 {{ HTMLElement("output") }} 、 {{ HTMLElement("progress") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea")}}表明是元件的所有者的形式。
high{{ HTMLElement("meter") }}表示下界的上限範圍。
keytype{{ HTMLElement("keygen") }}指定鍵所產生的類型。
list{{ HTMLElement("input") }}標識的預定義的選項的列表,以向用戶建議。
low{{ HTMLElement("meter") }}指示上限較低的範圍內。
max{{ HTMLElement("input") }} 、 {{ HTMLElement("meter") }} 、 {{ HTMLElement("progress") }}指示所允許的最大值。
maxlength{{ HTMLElement("input") }} 、 {{ HTMLElement("textarea") }}定義了在元件允許的字符的最大數目。
method{{HTMLElement("form")}}定義提交表單時使用的HTTP方法。可GET(默認)或POST。
min{{ HTMLElement("input") }} 、 {{ HTMLElement("meter") }}指示所允許的最小值。
multiple{{ HTMLElement("input") }}、 {{ HTMLElement("select") }}表示是否多個值所用的類型的輸入可以輸入電子郵件文件
name{{ HTMLElement("button") }} 、 {{ HTMLElement("form") }} 、 {{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("output") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea") }}該元素的名稱。例如所使用的服務器,以確定在表單提交的字段。
novalidate{{ HTMLElement("form") }}此屬性表明,當提交表單應該無法通過驗證。
optimum{{ HTMLElement("meter") }}表示最佳數值。
pattern{{ HTMLElement("input") }}定義一個正則表達式元素的值將針對驗證。
placeholder{{ HTMLElement("input") }}、 {{ HTMLElement("textarea") }}提供一個提示什麼可以在字段中輸入的用戶。
readonly{{ HTMLElement("input") }} 、 {{ HTMLElement("textarea") }}指示該元素是否可以編輯或沒有。
required{{ HTMLElement("input") }} 、 {{ HTMLElement("select") }}、 {{ HTMLElement("textarea") }}指示此元素是否必填。
rows{{ HTMLElement("textarea") }}限定在一個textarea的行數。
selected{{ HTMLElement("option") }}定義了將在頁面加載所選的值。
size{{ HTMLElement("input") }}、 {{ HTMLElement("select") }}限定了元件的寬度(以像素為單位)。如果該元素的類型的屬性是文本密碼那麼它的字符數。
src{{ HTMLElement("img") }}可嵌入內容的URL。
step{{ HTMLElement("input") }}
target{{ HTMLElement("form") }}
type{{ HTMLElement("button") }} 、 {{ HTMLElement("input") }}限定了元件的類型。
usemap{{ HTMLElement("img") }}
value{{ HTMLElement("button") }}、 {{ HTMLElement("option") }}、 {{ HTMLElement("input") }}、 {{ HTMLElement("meter") }}、 {{ HTMLElement("progress") }}定義了將被顯示在頁面上的負載元件的默認值。
wrap{{ HTMLElement("textarea") }}指示文本是否應被包裹或沒有。
+ +

規範性引用文件

+ + + +
+
+
diff --git a/files/zh-tw/learn/how_to_contribute/index.html b/files/zh-tw/learn/how_to_contribute/index.html deleted file mode 100644 index f8a864b98d..0000000000 --- a/files/zh-tw/learn/how_to_contribute/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: 如何建設 MDN 學習專區 -slug: Learn/How_to_contribute -tags: - - Documentation - - 初學者 - - 貢獻 -translation_of: Learn/How_to_contribute ---- -
{{LearnSidebar}}
- -

無論你是初來乍到、抑或尋至深處無怨尤、都應該是對貢獻 MDN 學習專區起了興趣吧。那很棒!

- -

在這裡,你會看到該如何改進 MDN 學習專區的內容。視你的時間多寡、以及你是初學者網路開發者教師而定,有一些你可以完成的事情。

- -
-

注意:你可以在如何撰寫幫助別人理解 Web 的文章裡面找到指引如何撰寫學習專區的新文章。

-
- -

找到特定的任務

- -

貢獻者們使用 Trello board 來組織工作事務。你可以透過這個方法,找出某個專案的工作。要加入的話,只要 建立一個 Trello 的帳號、然後去 ping Chris Mills 叫他給你撰寫 board 的權限。

- -

Contributing is a great way to have some fun while learning new stuff. If you ever feel lost or have questions, don't hesitate to reach us on our mailing list or IRC channel (see at the bottom of this page for details). Chris Mills is the topic driver for the Learning Area — you could also try pinging him directly.

- -

接下來的章節,會提供一些在你所能下的常見點子。

- -

我是初學者

- -

真棒!初學者在學習專區的創建與給予回饋,不但重要還很寶貴。身為目標閱聽者的你能在文章方面,提供令你成為團內重要成員的獨特觀點。如果你透過這些文章學習卻碰上問題、或是在某些地方稿不清楚,你可以自己去改它、或告訴我們以便我們修正之。

- -

我們建議你可以透過以下方法貢獻:

- -
-
給我們的文章添加標籤(約五分鐘)
-
給 MDN 的文章添加標籤,是向 MDN 貢獻的最簡單方法。我們有很多功能會透過標籤助以呈現內文資訊,所以幫忙標籤的建設相當寶貴。從沒有任何標籤的術語表以及學習專區開始吧。
-
閱讀並評價術語表(約五分鐘)
-
我們需要身為初學者的眼光,來檢視我們的內容。如果你發現某個術語難以理解,就表示該術語需要改進。你可以作任何認為有需要的更動。如果你不認為自己有修改該術語的技能,至少請透過我們的郵件清單告訴我們。
-
撰寫新的術語(約二十分鐘)
-
這是最有效的新技能學習法。選一個你想理解的概念去研究。接著,撰寫這個術語。和別人解釋,是「固著」你腦內知識的好方法。既幫自己理解所知、也幫了其他人。利人利己,大家都贏!
-
閱讀並評價術語表學習專區的文章(約兩小時)
-
和閱讀術語表差不多,但因為文章會更長了些,所以要花更多時間。
-
- -

我是網路開發者

- -

好極了!我們需要你的技能,來確保我們教給初學者的內容正確無誤。因為這裡的宗旨是理解網路,請確保解釋儘可能簡單,但不致毫無用處。比起過度精確,可以理解才是最重要的。

- -
-
閱讀並評價術語表(約五分鐘)
-
我們需要你確認文章的內容是正確又不過於艱澀難懂的。請你變更任何你認為有必要改善的地方。如果你想要在做變更之前討論一下內容,歡迎透過 our mailing list 或 IRC channel通知我們。
-
撰寫新的術語(約二十分鐘)
-
闡明術語是一個簡單又精確的學習方式,初學者還會感激你。我們有很多尚未定義的用詞需要你的協助,挑一個你擅長的吧。
-
閱讀並評價術語表學習專區的文章(約兩小時)
-
這跟評價數語表一樣(如上述),只是這些文章的篇幅更常,需要花更多的時間。
-
撰寫新的學習專區文章 (約四小時或更多)
-
MDN缺少簡單易懂的網頁技術相關文章(例如HTML, CSS, JavaScript)。我們也有較舊的文章需要重新審視並修正,請你將技能發揮到極致,讓初學者也能使用網頁技術。
-
提供練習題、範例或是互動式的教學工具。(? 小時)
-
我們所有的文章都需要 "active learning" 的素材在內,因為讓人們學習的最好途徑就是讓他們自己實作。這些素材會是練習題或互動式的內容,能協助使用者將文章內詳述的概念實際運用。有很多方式能夠製作 "active learning" 的內容,像是使用 JSFiddle 或相似的工具提供範例程式碼,或使用Thimble提供互動式的內容。 好好發揮你得創造力吧!
-
- -

我是教師

- -

MDN 有著精良的技術史,但我們對教導新人觀念的最佳方法,缺乏深入了解。針對這方面,我們需要借重做為教師或導師身份的你。你能幫我們確保給讀者們的內容,有著良好而實用的教育路徑(educational track)。

- -
-
閱讀並評價術語表(約十五分鐘)
-
Check out a glossary entry and feel free to make any changes you think are necessary. If you want to discuss the content before editing, ping us on our mailing list or IRC channel.
-
撰寫新的術語(約一小時)
-
Clear, simple definitions of terms and basic overviews of concepts in the glossary are critical in meeting beginners' needs. Your experience as an educator can help create excellent glossary entries; we have many undefined terms which need your attention. Pick one and go for it.
-
添加實例或圖表至文章 (約一小時)
-
As you might know, illustrations are an invaluable part of any learning content. This is something we often lack on MDN and your skills can make a difference in that area. Check out the articles that lack illustrative content and pick one you'd like to create graphics for.
-
閱讀並審核教學文章 (約兩小時)
-
This is similar to reviewing glossary entries (see above), but it requires more time since the articles are typically quite a bit longer.
-
撰寫新的教學文章 (約四小時)
-
We need simple, straightforward articles about the Web ecosystem and other functional topics around it. Since these learning articles need to be educational rather than trying to literally cover everything there is to know, your experience in knowing what to cover and how will be a great asset.
-
建立練習題,測驗或是互動式的學習工具(? 小時)
-
All our learning articles require "active learning" materials. Such materials are exercises or interactive content which help a user learn to use and expand upon the concepts detailed in an article.  There are lots of things you can do here, from creating quizzes to building fully hackable interactive content with Thimble. Unleash your creativity!
-
建立學習途徑 (? 小時)
-
In order to provide progressive and comprehensible tutorials, we need to shape our content into pathways. It's a way to gather existing content and figure out what is missing to create a learning article to write.
-
diff --git a/files/zh-tw/learn/html/forms/how_to_structure_an_html_form/index.html b/files/zh-tw/learn/html/forms/how_to_structure_an_html_form/index.html deleted file mode 100644 index b403666795..0000000000 --- a/files/zh-tw/learn/html/forms/how_to_structure_an_html_form/index.html +++ /dev/null @@ -1,315 +0,0 @@ ---- -title: 如何建構 HTML 表單 -slug: Learn/HTML/Forms/How_to_structure_an_HTML_form -translation_of: Learn/Forms/How_to_structure_a_web_form ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}
- -

有了基礎後,我們就能探討表單元素,所提供的結構與文意之詳細資訊;還有各表單部份的相異之處。

- - - - - - - - - - - - -
先決條件:對電腦還有 HTML 有基本理解。
目標:理解如何構建 HTML 表單並給予無障礙的語意化。
- -

表單表單的彈性化令其成為 HTML 最複雜的結構之一。你能使用專用的表單元素和屬性,來構建任何類型的基本表單。使用正確的 HTML 表單結構能讓確保表單可用、且無障礙

- -

<form> 元素

- -

{{HTMLElement("form")}} 元素會形式上的定義表單和決定行為屬性。每次建立 HTML 表單時,都必須使用 form 元素;並將所有內容嵌進去。大多數的輔助技術與瀏覽器套件,都能抓到 {{HTMLElement("form")}} 元素,並實做特殊的 hook,使其更易於使用。

- -

我們之前就講過這件事了。

- -
注意:絕對不能在表單裡面再嵌入表單。這會讓表單行為變得難以理解,所以是一個壞主意。
- -

你可以從表單外面控制 {{HTMLElement("form")}} 。這麼做的話,除非使用 form 將其與表單關聯,否則該操作預設上和任何表單無關。引入此功能是為了可以在即使該操作未嵌在表單中,其依舊能顯式地將操作與表單綁定。

- -

接下來就開始探討表單裡面可能會嵌入什麼吧。

- -

<fieldset> and <legend> 元素

- -

{{HTMLElement("fieldset")}} 元素能方便地建立用途相近、樣式及語意化都很方便的小部件組(groups of widgets)。你可以透過添加 {{HTMLElement("legend")}} 來給 {{HTMLElement("fieldset")}} 的內部開頭添加標籤。{{HTMLElement("legend")}} 的文字內容能描述 {{HTMLElement("legend")}} 目的。

- -

多數輔助科技會在 {{HTMLElement("legend")}} 元素被 {{HTMLElement("fieldset")}} 包住時偵測並使用它。比如說 JawsNVDA 之類的螢幕報讀器就會在讀到每個控件的標籤前,讀出 legend 的內容。

- -

下面就有一個示例:

- -
<form>
-  <fieldset>
-    <legend>Fruit juice size</legend>
-    <p>
-      <input type="radio" name="size" id="size_1" value="small">
-      <label for="size_1">Small</label>
-    </p>
-    <p>
-      <input type="radio" name="size" id="size_2" value="medium">
-      <label for="size_2">Medium</label>
-    </p>
-    <p>
-      <input type="radio" name="size" id="size_3" value="large">
-      <label for="size_3">Large</label>
-    </p>
-  </fieldset>
-</form>
- -
-

:你可以在fieldset-legend.html 觀察範例(或著觀察這個動態互動)。

-
- -

在閱讀表單時,螢幕報讀器會針對第一個小部件組,說出「Fruit juice size small」、接著針對第二個小部件組,說出「Fruit juice size medium」、第三個則是「Fruit juice size large」。

- -

這個示例的是最重要的用法之一:每次有一組 radio 按鈕時,就該在裡面放一個 {{HTMLElement("fieldset")}} 元素。{{HTMLElement("fieldset")}} 也能用在表單的其他地方。理想上,要是表單一長,就要把他放到其他頁面。但如果做不到這點,那將不同的相關部分,放在不同的 fieldsets 之中,也可以提高可用性。

- -

由於 {{HTMLElement("fieldset")}} 對輔助技術的影響,這個元素是建立無障礙表單的基石,但請注意不要濫用這個元素。可以的話,聽聽螢幕報讀是怎麼講的。如果踢起來怪怪的,那就試著改進表單。

- -

<label> 元素

- -

正如上篇文章中所見,{{HTMLElement("label")}} 元素是定義 HTML 表單控件的正式方法。如果要構建無障礙的表單,這是最重要的元素:正確實做後,螢幕閱讀器會說出表單元素標籤、以及相關說明,同時也對有視力的用戶很有用。以這個例子為例,我們在上一篇文章中看過:

- -
<label for="name">Name:</label> <input type="text" id="name" name="user_name">
- -

<label> 元素透過 for 屬性與 <input> 元素的 id 屬性正確連結後,螢幕閱讀器就會讀出「Name, edit text」這樣的文字。

- -

還有另一種控制標籤與表單控件關聯的方法:那就是把表單控件嵌在 <label> 元素裡面,以便隱式關聯。

- -
<label for="name">
-  Name: <input type="text" id="name" name="user_name">
-</label>
- -

但即使在這種情況下,最好還是設置 for 屬性,以確保所有輔具都能理解標籤和控件之間的關係。

- -

如果沒有標籤、或著說表單控件沒有被顯式或隱式關聯,螢幕閱讀器會讀出沒啥幫助的「Edit text blank」。

- -

標籤也能點喔!

- -

使用標籤的另一個好處,就是能在點選該標籤後,啟動相對應的小部件。這種功能在控制文字輸入的時候會很好用:用戶點選標籤時就可以 focus 到 input 那邊。這對 button 與 checkbox 尤其有用:因為點選的區域可能很小,因此使它盡可能簡單地啟用,會是很有用的。

- -

例如在下面的示例中,點選「I like cherry」標籤文字後會切換 taste_cherry checkbox 的點選狀態:

- -
<form>
-  <p>
-    <input type="checkbox" id="taste_1" name="taste_cherry" value="cherry">
-    <label for="taste_1">I like cherry</label>
-  </p>
-  <p>
-    <input type="checkbox" id="taste_2" name="taste_banana" value="banana">
-    <label for="taste_2">I like banana</label>
-  </p>
-</form>
- -
-

:你可以在 checkbox-label.html 觀察示例(這裡有展示版本!

-
- -

多個標籤

- -

嚴格來說,一個小部件組能放很多個標籤,但由於部分輔助科技處理上會有問題,所以這也不是個好點子。如果有多個標籤,請試著把巢狀各個小部件,並在裡面只安插一個 {{htmlelement("label")}} 元素。

- -

來看看這個例子:

- -
<p>Required fields are followed by <abbr title="required">*</abbr>.</p>
-
-<!-- So this: -->
-<div>
-  <label for="username">Name:</label>
-  <input id="username" type="text" name="username">
-  <label for="username"><abbr title="required" aria-label="required">*</abbr></label>
-</div>
-
-<!-- would be better done like this: -->
-<div>
-  <label for="username">
-    <span>Name:</span>
-    <input id="username" type="text" name="username">
-    <abbr title="required" aria-label="required">*</abbr>
-  </label>
-</div>
-
-<!-- But this is probably best: -->
-<div>
-  <label for="username">Name: <abbr title="required" aria-label="required">*</abbr></label>
-  <input id="username" type="text" name="username">
-</div>
- -

{{EmbedLiveSample("Multiple_labels", 120, 120)}}

- -

The paragraph at the top states a rule for required elements. The rule must be included before it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. While this helps inform users what an asterisk means, it can not be relied upon. A screen reader will speak an asterisk as "star" when encountered. When hovered by a sighted mouse user, "required" should appear, which is achieved by use of the title attribute. Titles being read aloud depend on the screen reader's settings, so it is more reliable to also include the aria-label attribute, which is always read by screen readers.

- -

The above variants increase in effectiveness as you go through them:

- - - -
-

Note: You might get slightly different results, depending on your screenreader. This was tested in VoiceOver (and NVDA behaves similarly). We'd love to hear about your experiences too.

-
- -
-

Note: You can find this example on GitHub as required-labels.html (see it live also). don't test the example with 2 or 3 of the versions uncommented — screenreaders will definitely get confused if you have multiple labels AND multiple inputs with the same ID!

-
- -

建立表單所常用的 HTML 結構

- -

Beyond the structures specific to web forms, it's good to remember that form markup is just HTML. This means that you can use all the power of HTML to structure a web form.

- -

As you can see in the examples, it's common practice to wrap a label and its widget with a {{HTMLElement("li")}} element within a {{HTMLElement("ul")}} or {{HTMLElement("ol")}} list. {{HTMLElement("p")}} and {{HTMLElement("div")}} elements are also commonly used. Lists are recommended for structuring multiple checkboxes or radio buttons.

- -

In addition to the {{HTMLElement("fieldset")}} element, it's also common practice to use HTML titles (e.g. {{htmlelement("h1")}}, {{htmlelement("h2")}}) and sectioning (e.g. {{htmlelement("section")}}) to structure complex forms.

- -

Above all, it is up to you to find a comfortable coding style that results in accessible, usable forms. Each separate section of functionality should be contained in a separate {{htmlelement("section")}} element, with {{htmlelement("fieldset")}} elements to contain radio buttons.

- -

主動學習:建立表單結構

- -

Let's put these ideas into practice and build a slightly more involved form — a payment form. This form will contain a number of control types that you may not yet understand. Don't worry about this for now; you'll find out how they work in the next article (Basic native form controls). For now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why.

- -
    -
  1. To start with, make a local copy of our blank template file and the CSS for our payment form in a new directory on your computer.
  2. -
  3. Apply the CSS to the HTML by adding the following line inside the HTML {{htmlelement("head")}}: -
    <link href="payment-form.css" rel="stylesheet">
    -
  4. -
  5. Next, create your form by adding the outer {{htmlelement("form")}} element: -
    <form>
    -
    -</form>
    -
  6. -
  7. Inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: -
    <h1>Payment form</h1>
    -<p>Required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p>
    -
  8. -
  9. Next we'll add a larger section of code into the form, below our previous entry. Here you'll see that we are wrapping the contact information fields inside a distinct {{htmlelement("section")}} element. Moreover, we have a set of two radio buttons, each of which we are putting inside its own list ({{htmlelement("li")}}) element. We also have two standard text {{htmlelement("input")}}s and their associated {{htmlelement("label")}} elements, each contained inside a {{htmlelement("p")}}, and a password input for entering a password. Add this code to your form: -
    <section>
    -    <h2>Contact information</h2>
    -    <fieldset>
    -      <legend>Title</legend>
    -      <ul>
    -          <li>
    -            <label for="title_1">
    -              <input type="radio" id="title_1" name="title" value="K" >
    -              King
    -            </label>
    -          </li>
    -          <li>
    -            <label for="title_2">
    -              <input type="radio" id="title_2" name="title" value="Q">
    -              Queen
    -            </label>
    -          </li>
    -          <li>
    -            <label for="title_3">
    -              <input type="radio" id="title_3" name="title" value="J">
    -              Joker
    -            </label>
    -          </li>
    -      </ul>
    -    </fieldset>
    -    <p>
    -      <label for="name">
    -        <span>Name: </span>
    -        <strong><abbr title="required">*</abbr></strong>
    -      </label>
    -      <input type="text" id="name" name="username">
    -    </p>
    -    <p>
    -      <label for="mail">
    -        <span>E-mail: </span>
    -        <strong><abbr title="required">*</abbr></strong>
    -      </label>
    -      <input type="email" id="mail" name="usermail">
    -    </p>
    -    <p>
    -      <label for="pwd">
    -        <span>Password: </span>
    -        <strong><abbr title="required">*</abbr></strong>
    -      </label>
    -      <input type="password" id="pwd" name="password">
    -    </p>
    -</section>
    -
  10. -
  11. The second <section> of our form is the payment information. We have three distinct controls along with their labels, each contained inside a <p>. The first is a drop-down menu ({{htmlelement("select")}}) for selecting credit card type. The second is an <input> element of type tel, for entering a credit card number; while we could have used the number type, we don't want the number's spinner UI. The last one is an <input> element of type date, for entering the expiration date of the card; this one will come up with a date picker widget in supporting browsers, and fall back to a normal text input in non-supporting browsers. These newer input types are reintroduced in The HTML5 input types.
    -
    - Enter the following below the previous section: -
    <section>
    -    <h2>Payment information</h2>
    -    <p>
    -      <label for="card">
    -        <span>Card type:</span>
    -      </label>
    -      <select id="card" name="usercard">
    -        <option value="visa">Visa</option>
    -        <option value="mc">Mastercard</option>
    -        <option value="amex">American Express</option>
    -      </select>
    -    </p>
    -    <p>
    -      <label for="number">
    -        <span>Card number:</span>
    -        <strong><abbr title="required">*</abbr></strong>
    -      </label>
    -      <input type="tel" id="number" name="cardnumber">
    -    </p>
    -    <p>
    -      <label for="date">
    -        <span>Expiration date:</span>
    -        <strong><abbr title="required">*</abbr></strong>
    -        <em>formatted as mm/dd/yyyy</em>
    -      </label>
    -      <input type="date" id="date" name="expiration">
    -    </p>
    -</section>
    -
  12. -
  13. The last section we'll add is a lot simpler, containing only a {{htmlelement("button")}} of type submit, for submitting the form data. Add this to the bottom of your form now: -
    <p> <button type="submit">Validate the payment</button> </p>
    -
  14. -
- -

You can see the finished form in action below (also find it on GitHub — see our payment-form.html source and running live):

- -

{{EmbedLiveSample("A_payment_form","100%",620, "", "Learn/Forms/How_to_structure_a_web_form/Example")}}

- -

結論

- -

你現在擁有了正確建構 HTML 表單的所有知識。接下來將介紹本章介紹的許多功能。在下一篇文章中,將詳細探討如何使用各種不同類型的表單小部件,來收集用戶的訊息。

- -

參見

- - - -

{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}

- -

在本模塊

- - - -

Advanced Topics

- - diff --git a/files/zh-tw/learn/html/forms/index.html b/files/zh-tw/learn/html/forms/index.html deleted file mode 100644 index 589880794f..0000000000 --- a/files/zh-tw/learn/html/forms/index.html +++ /dev/null @@ -1,359 +0,0 @@ ---- -title: 網站表單-與數據合作 -slug: Learn/HTML/Forms -tags: - - Featured - - Forms - - Guide - - HTML - - NeedsTranslation - - TopicStub - - Web - - 待翻譯 -translation_of: Learn/Forms ---- -

這篇指南提供了一系列的文章,幫你掌握HTML表單的基本知識。對於與使用者互動,網站表單是一項十分有力的工具,最常使用於用戶數據蒐集,或控制使用者介面。但由於一些歷史與技術上的因素,並沒有顯著的方法發揮表單的潛力。在下面的指引中,我們將介紹網站表單所有基本面向,包括標記他們的HTML結構、設定控制器樣式、驗證數據及將數距提送至伺服器

- -

參考文章列表

- -
    -
  1. 我的第一個HTML表單
  2. -
  3. 如何構建 HTML 表單
  4. -
  5. 本機表單控件
  6. -
  7. CSS和HTML表單 -
      -
    1. 造型HTML表單
    2. -
    3. HTML表單高級造型
    4. -
    5. 表單控件屬性兼容表
    6. -
    -
  8. -
  9. 發送和檢索表單數據
  10. -
  11. 數據表單驗證
  12. -
  13. 如何創建自定義表單控件
  14. -
  15. 通過JavaScript發送形式 -
      -
    1. 使用FORMDATA 對象
    2. -
    -
  16. -
  17. 在傳統的瀏覽器的HTML表單
  18. -
- -

HTML 文件

- -

HTML 元素

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
HTML 元素元素的 DOM interface說明
{{HTMLElement("button")}}{{domxref("HTMLButtonElement")}}按鈕元素表示一個可點擊的按鈕。
{{HTMLElement("datalist")}}{{domxref("HTMLDataListElement")}}數據列表元素包含了一組  {{ HTMLElement("option") }}  表示對其他表單元素的值可能的選擇要素。
{{HTMLElement("fieldset")}}{{domxref("HTMLFieldSetElement")}}字段集是用來在表單中的組數表單元素。
{{HTMLElement("form")}}{{domxref("HTMLFormElement")}}形式元素表示的文件的一部分,它包含使用戶能夠提交信息給web服務器的交互元件。
{{HTMLElement("input")}}{{domxref("HTMLInputElement")}}該  輸入元素用於創建表格的交互式控制。
{{HTMLElement("keygen")}}{{domxref("HTMLKeygenElement")}}所述凱基元素存在,以促進生成的密鑰材料,並提交了公開密鑰的作為HTML形式的一部分
{{HTMLElement("label")}}{{domxref("HTMLLabelElement")}}標籤元素代表一個項目在用戶界面的標題
{{HTMLElement("legend")}}{{domxref("HTMLLegendElement")}}傳說元素代表一個標題為其父 {{ HTMLElement("fieldset") }} 的內容。
{{HTMLElement("meter")}}{{domxref("HTMLMeterElement")}}所述元素表示一個已知的範圍內的任一標量值或分數值。
{{HTMLElement("optgroup")}}{{domxref("HTMLOptGroupElement")}}OPTGROUP元素創建一個 {{ HTMLElement("select") }}  元素中的一組選項。
{{HTMLElement("option")}}{{domxref("HTMLOptionElement")}}在HTML 選項元素用於創建表示  {{ HTMLElement("select") }} ,一個 {{ HTMLElement("optgroup") }}  {{ HTMLElement("datalist") }} 元素中的項目的控制。
{{HTMLElement("output")}}{{domxref("HTMLOutputElement")}}輸出元素表示一個計算的結果。
{{HTMLElement("progress")}}{{domxref("HTMLProgressElement")}}進展元素用於查看任務的完成進度。
{{HTMLElement("select")}}{{domxref("HTMLSelectElement")}}選擇元素代表呈現一個選項菜單的控制。
{{HTMLElement("textarea")}}{{domxref("HTMLTextAreaElement")}}textarea的元素代表多行純文本編輯控制。
- -
-

注:所有的表單元素,因為所有的HTML元素,支持 {{domxref("HTMLElement")}} DOM接口。

-
- -

HTML 屬性

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
屬性能使用該屬性的 HTML 元素說明
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}的類型列表服務器接受,通常是文件類型。
accept-charset{{ HTMLElement("form") }}支持的字符集列表。
action{{ HTMLElement("form") }}一個程序處理通過表單提交的信息的URI。
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}指示是否在這個表單控件可以在默認情況下有其值由瀏覽器自動完成。
autofocus{{ HTMLElement("button") }}、 {{ HTMLElement("input") }}、 {{ HTMLElement("keygen") }}、 {{ HTMLElement("select") }}、 {{ HTMLElement("textarea") }}該元素應該在頁面加載後自動聚焦。
challenge{{ HTMLElement("keygen") }}即隨著公共密鑰提交的挑戰字符串。
checked{{ HTMLElement("input") }}指示是否應將元素在頁面加載檢查。
cols{{ HTMLElement("textarea") }}限定在一個textarea的列數。
data{{ HTMLElement("object") }}指定的資源的URL。
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}
disabled{{ HTMLElement("button") }} 、{{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("optgroup") }} 、 {{ HTMLElement("option") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea")}}表明用戶是否可以與元件進行交互。
enctype{{ HTMLElement("form") }}定義當表單數據的內容類型的方法是POST。
for{{ HTMLElement("label") }}、 {{ HTMLElement("output") }}描述了屬於這一種元素。
form{{ HTMLElement("button") }} 、 {{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("label") }} 、 {{ HTMLElement("meter") }} 、 {{ HTMLElement("object") }} 、 {{ HTMLElement("output") }} 、 {{ HTMLElement("progress") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea")}}表明是元件的所有者的形式。
high{{ HTMLElement("meter") }}表示下界的上限範圍。
keytype{{ HTMLElement("keygen") }}指定鍵所產生的類型。
list{{ HTMLElement("input") }}標識的預定義的選項的列表,以向用戶建議。
low{{ HTMLElement("meter") }}指示上限較低的範圍內。
max{{ HTMLElement("input") }} 、 {{ HTMLElement("meter") }} 、 {{ HTMLElement("progress") }}指示所允許的最大值。
maxlength{{ HTMLElement("input") }} 、 {{ HTMLElement("textarea") }}定義了在元件允許的字符的最大數目。
method{{HTMLElement("form")}}定義提交表單時使用的HTTP方法。可GET(默認)或POST。
min{{ HTMLElement("input") }} 、 {{ HTMLElement("meter") }}指示所允許的最小值。
multiple{{ HTMLElement("input") }}、 {{ HTMLElement("select") }}表示是否多個值所用的類型的輸入可以輸入電子郵件文件
name{{ HTMLElement("button") }} 、 {{ HTMLElement("form") }} 、 {{ HTMLElement("fieldset") }} 、 {{ HTMLElement("input") }} 、 {{ HTMLElement("keygen") }} 、 {{ HTMLElement("output") }} 、 {{ HTMLElement("select") }} 、 {{ HTMLElement("textarea") }}該元素的名稱。例如所使用的服務器,以確定在表單提交的字段。
novalidate{{ HTMLElement("form") }}此屬性表明,當提交表單應該無法通過驗證。
optimum{{ HTMLElement("meter") }}表示最佳數值。
pattern{{ HTMLElement("input") }}定義一個正則表達式元素的值將針對驗證。
placeholder{{ HTMLElement("input") }}、 {{ HTMLElement("textarea") }}提供一個提示什麼可以在字段中輸入的用戶。
readonly{{ HTMLElement("input") }} 、 {{ HTMLElement("textarea") }}指示該元素是否可以編輯或沒有。
required{{ HTMLElement("input") }} 、 {{ HTMLElement("select") }}、 {{ HTMLElement("textarea") }}指示此元素是否必填。
rows{{ HTMLElement("textarea") }}限定在一個textarea的行數。
selected{{ HTMLElement("option") }}定義了將在頁面加載所選的值。
size{{ HTMLElement("input") }}、 {{ HTMLElement("select") }}限定了元件的寬度(以像素為單位)。如果該元素的類型的屬性是文本密碼那麼它的字符數。
src{{ HTMLElement("img") }}可嵌入內容的URL。
step{{ HTMLElement("input") }}
target{{ HTMLElement("form") }}
type{{ HTMLElement("button") }} 、 {{ HTMLElement("input") }}限定了元件的類型。
usemap{{ HTMLElement("img") }}
value{{ HTMLElement("button") }}、 {{ HTMLElement("option") }}、 {{ HTMLElement("input") }}、 {{ HTMLElement("meter") }}、 {{ HTMLElement("progress") }}定義了將被顯示在頁面上的負載元件的默認值。
wrap{{ HTMLElement("textarea") }}指示文本是否應被包裹或沒有。
- -

規範性引用文件

- - - -
-
-
diff --git "a/files/zh-tw/learn/html/multimedia_and_embedding/html\344\270\255\347\232\204\345\234\226\347\211\207/index.html" "b/files/zh-tw/learn/html/multimedia_and_embedding/html\344\270\255\347\232\204\345\234\226\347\211\207/index.html" deleted file mode 100644 index 5a2dfd7eff..0000000000 --- "a/files/zh-tw/learn/html/multimedia_and_embedding/html\344\270\255\347\232\204\345\234\226\347\211\207/index.html" +++ /dev/null @@ -1,502 +0,0 @@ ---- -title: HTML中的圖片 -slug: Learn/HTML/Multimedia_and_embedding/HTML中的圖片 -translation_of: Learn/HTML/Multimedia_and_embedding/Images_in_HTML ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}
- -

最初的網頁最初的發展階段,只是文字。而只有文字想當然爾令網頁讀起來十分的枯燥乏味。然而幸運的是沒有多久,將圖片(以及其他更有趣的內容類型)嵌入網頁的功能就誕生了。 在多媒體嵌入網頁的學習中,從<img>元素開始是相對適當,因為該元素用於在網頁中嵌入簡單的圖像。 在本文中,我們將研究如何深入使用它,包括在網頁中嵌入簡單圖像的基礎知識,使用<figure>增加標題說明以做註釋,以及詳細說明它與CSS背景圖片的關係。

- - - - - - - - - - - - -
課成需求:基本的電腦操作, 安裝軟體的能力, 處理檔案的基本能力, 熟悉最基本的HTML的 (如HTML入門中所述
學習目標:了解如何在HTML中嵌入簡單的圖片,為它們加上標題註釋,以及HTML圖片與CSS背景圖片之間的關係。
- -

如何將圖片放入網頁中?

- -

為了在網頁上放置一個簡單的圖像,我們使用<img>元素。 這是一個空元素(意味著它沒有文本內容或結束標記),並需要至少一個屬性(src)(有時稱為其完整標題,source)才有用。 src屬性包含指向要嵌入頁面的圖像的路徑,該路徑可以是相對路徑或絕對路徑URL,與<a>元素中的href屬性相同。

- -
-

提醒: 在繼續之前,您應該閱讀有關URL和路徑的快速入門,以複習相對路徑和絕對路徑URL

-
- -

舉例來說, 如果您的圖片名為 dinosaur.jpg 且與HTML檔案位於同一資料夾中,可以這樣嵌入圖片:

- -
<img src="dinosaur.jpg">
- -

如果圖片位於名為images的資料夾中,且該目錄與HTML頁面位於同一資料夾(Google建議這樣的編排,以利於SEO /索引目的),則應將其嵌入如下:

- -
<img src="images/dinosaur.jpg">
- -

像這樣.

- -
-

提醒: 搜索引擎還會讀取圖片名稱,並將其納入SEO中。 因此您應該為圖片提供一個描述性的檔名。 例如 dinosaur.jpg 的命名方式會比 img835.png 更好。

-
- -

你也可以用絕對路徑URL來嵌入圖片,例如

- -
<img src="https://www.example.com/images/dinosaur.jpg">
- -

但這麼做是沒有意義的,因為它只會使瀏覽器執行更多工作,瀏覽器需重複執行從DNS服務器中搜尋IP地址等等工作。您應將網站上的圖片與HTML存放在同一個伺服器上。

- -
-

注意: 大多數圖像均受版權保護。 請勿在你的網站上隨意顯示圖片,除非:

- - - -

侵犯版權是違法及不道德的。 此外,切勿將src屬性指向您未被授權的他人網站上的圖便。 這稱為“熱連結”。再次重申,竊取某人的頻寬是違法的,且這會減慢您網站的速度。此外當別人變更、移除或換上令人尷尬的內容時你將無法做出改變。

-
- -

我們上面的程式碼將有以下結果:

- -

A basic image of a dinosaur, embedded in a browser, with "Images in HTML" written above it

- -
-

提醒: <img>和<video>之類的元素有時也稱為替換元素。 這是因為元素的內容和圖片大小是由外部(例如圖片或影音檔)所定義的,而不是由元素的內容定義。

-
- -
-

提醒: 您可以從在Github上找到本節完成的示例(參見開源碼。)

-
- -

替代性文字

- -

我們下一個要看的屬性是alt。 它的功能算是圖片的文字描述,應用於因網路連接速度慢而無法看到/顯示圖片或需要長時間來跑圖等等情況。 例如,上面的程式碼我們可以像這樣修改:

- -
<img src="images/dinosaur.jpg"
-     alt="The head and torso of a dinosaur skeleton;
-          it has a large head with long sharp teeth">
- -

測試替代文字最簡單方法是故意拼錯檔名。 例如,如果我們的圖片名稱為dinosooooor.jpg,則瀏覽器將不會顯示該圖片,而是顯示alt文本:The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.

- -

那麼,為什麼您會看到或需要替代文字? 它可以派上用場的原因有很多:

- - - -

您應該在alt屬性中確切寫些什麼? 這取決於圖片為何而出現;也就是說,如果圖片不顯示,您將損失什麼:

- - - -

本質上,關鍵是即使在看不見圖片的情況下也能提供相同的體驗。這樣可以確保所有使用者都不會丟失任何內容。嘗試在瀏覽器中關閉圖像,然後查看外觀。您很快就會意識到,如果看不到圖片,替代文字會很有幫助。

- -
-

Note: For more information, see our guide to Text Alternatives.

-
- -

寬與高

- -

You can use the width and height attributes to specify the width and height of your image. You can find your image's width and height in a number of ways. For example on the Mac you can use Cmd + I to get the info display up for the image file. Returning to our example, we could do this:

- -
<img src="images/dinosaur.jpg"
-     alt="The head and torso of a dinosaur skeleton;
-          it has a large head with long sharp teeth"
-     width="400"
-     height="341">
- -

This doesn't result in much difference to the display, under normal circumstances. But if the image isn't being displayed, for example, the user has just navigated to the page, and the image hasn't yet loaded, you'll notice the browser is leaving a space for the image to appear in:

- -

The Images in HTML title, with dinosaur alt text, displayed inside a large box that results from width and height settings

- -

This is a good thing to do, resulting in the page loading quicker and more smoothly.

- -

However, you shouldn't alter the size of your images using HTML attributes. If you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. The image may also end up looking distorted, if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.

- -
-

Note: If you do need to alter an image's size, you should use CSS instead.

-
- -

圖片標題

- -

As with links, you can also add title attributes to images, to provide further supporting information if needed. In our example, we could do this:

- -
<img src="images/dinosaur.jpg"
-     alt="The head and torso of a dinosaur skeleton;
-          it has a large head with long sharp teeth"
-     width="400"
-     height="341"
-     title="A T-Rex on display in the Manchester University Museum">
- -

This gives us a tooltip on mouse hover, just like link titles:

- -

The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum

- -

However, this does not come recommended — title has a number of accessibility problems, mainly based around the fact that screen reader support is very unpredictable and most browsers won't show it unless you are hovering with a mouse (so e.g. no access to keyboard users). If you are interested in more information about this, read The Trials and Tribulations of the Title Attribute by Scott O'Hara.

- -

It is better to include such supporting information in the main article text, rather than attached to the image.

- -

實戰練習:嵌入圖片

- -

It is now your turn to play! This active learning section will have you up and running with a simple embedding exercise. You are provided with a basic {{htmlelement("img")}} tag; we'd like you to embed the image located at the following URL:

- -

https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

- -

Earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.

- -

We would also like you to:

- - - -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

- - - -

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

- -

用圖文和圖文標註說明圖像

- -

Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you from doing this:

- -
<div class="figure">
-  <img src="images/dinosaur.jpg"
-       alt="The head and torso of a dinosaur skeleton;
-            it has a large head with long sharp teeth"
-       width="400"
-       height="341">
-
-  <p>A T-Rex on display in the Manchester University Museum.</p>
-</div>
- -

This is ok. It contains the content you need, and is nicely stylable using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?

- -

A better solution, is to use the HTML5 {{htmlelement("figure")}} and {{htmlelement("figcaption")}} elements. These are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. Our above example could be rewritten like this:

- -
<figure>
-  <img src="images/dinosaur.jpg"
-       alt="The head and torso of a dinosaur skeleton;
-            it has a large head with long sharp teeth"
-       width="400"
-       height="341">
-
-  <figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>
-</figure>
- -

The {{htmlelement("figcaption")}} element tells browsers, and assistive technology that the caption describes the other content of the {{htmlelement("figure")}} element.

- -
-

Note: From an accessibility viewpoint, captions and {{htmlattrxref('alt','img')}} text have distinct roles. Captions benefit even people who can see the image, whereas {{htmlattrxref('alt','img')}} text provides the same functionality as an absent image. Therefore, captions and alt text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.

-
- -

A figure doesn't have to be an image. It is an independent unit of content that:

- - - -

A figure could be several images, a code snippet, audio, video, equations, a table, or something else.

- -

實戰練習:建立圖文標註

- -

In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:

- -
    -
  1. Wrap it in a {{htmlelement("figure")}} element.
  2. -
  3. Copy the text out of the title attribute, remove the title attribute, and put the text inside a {{htmlelement("figcaption")}} element below the image.
  4. -
- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

- - - -

{{ EmbedLiveSample('Playable_code_2', 700, 350, "", "", "hide-codepen-jsfiddle") }}

- -

CSS 背景圖片

- -

您還可以使用CSS將圖像嵌入網頁(JavaScript也可以,但這完全是另一回事了)。 CSSbackground-image屬性和其他background- *屬性用於控制背景圖片的放置。 例如要將背景圖片放置在頁面的每個段落上,可以執行以下操作:

- -
p {
-  background-image: url("images/dinosaur.jpg");
-}
- -

這種嵌入圖片的方式比HTML圖像更容易定位和控制。 那麼,為什麼還要用HTML嵌入圖片呢? 如上所述,CSS背景圖像僅用於裝飾。 如果您只是想在頁面上添加一些漂亮的東西以增強視覺效果,那很好。 但是,此類圖像根本沒有語義。 它們與文字不同,對於螢幕閱讀器是不可見的,依此類推。 這裡需要的是HTML圖片!

- -

總結來說,如果圖片在內容上具有含義,則應使用HTML圖像。 如果圖像純粹是裝飾性的,則應使用CSS背景圖片。

- -
-

提醒: 在我們的CSS主題中,您將學到更多關於CSS背景圖片的知識。

-
- -

試試看!

- -

您已經來到了本文的末端,但是您還記得最重要的內容嗎? 在繼續往下之前,這裡有些測驗讓您驗證看看您是否都學會了 — 測驗:HTML圖像

- -

總結

- -

目前就是這樣啦。 我們已經詳細介紹了圖片和標題說明。 在下一篇文章中我們將進一步介紹,如何使用HTML將視頻和音頻嵌入在網頁中。

- -

{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}

- -

在這個主題中

- - diff --git a/files/zh-tw/learn/html/multimedia_and_embedding/images_in_html/index.html b/files/zh-tw/learn/html/multimedia_and_embedding/images_in_html/index.html new file mode 100644 index 0000000000..5a2dfd7eff --- /dev/null +++ b/files/zh-tw/learn/html/multimedia_and_embedding/images_in_html/index.html @@ -0,0 +1,502 @@ +--- +title: HTML中的圖片 +slug: Learn/HTML/Multimedia_and_embedding/HTML中的圖片 +translation_of: Learn/HTML/Multimedia_and_embedding/Images_in_HTML +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}
+ +

最初的網頁最初的發展階段,只是文字。而只有文字想當然爾令網頁讀起來十分的枯燥乏味。然而幸運的是沒有多久,將圖片(以及其他更有趣的內容類型)嵌入網頁的功能就誕生了。 在多媒體嵌入網頁的學習中,從<img>元素開始是相對適當,因為該元素用於在網頁中嵌入簡單的圖像。 在本文中,我們將研究如何深入使用它,包括在網頁中嵌入簡單圖像的基礎知識,使用<figure>增加標題說明以做註釋,以及詳細說明它與CSS背景圖片的關係。

+ + + + + + + + + + + + +
課成需求:基本的電腦操作, 安裝軟體的能力, 處理檔案的基本能力, 熟悉最基本的HTML的 (如HTML入門中所述
學習目標:了解如何在HTML中嵌入簡單的圖片,為它們加上標題註釋,以及HTML圖片與CSS背景圖片之間的關係。
+ +

如何將圖片放入網頁中?

+ +

為了在網頁上放置一個簡單的圖像,我們使用<img>元素。 這是一個空元素(意味著它沒有文本內容或結束標記),並需要至少一個屬性(src)(有時稱為其完整標題,source)才有用。 src屬性包含指向要嵌入頁面的圖像的路徑,該路徑可以是相對路徑或絕對路徑URL,與<a>元素中的href屬性相同。

+ +
+

提醒: 在繼續之前,您應該閱讀有關URL和路徑的快速入門,以複習相對路徑和絕對路徑URL

+
+ +

舉例來說, 如果您的圖片名為 dinosaur.jpg 且與HTML檔案位於同一資料夾中,可以這樣嵌入圖片:

+ +
<img src="dinosaur.jpg">
+ +

如果圖片位於名為images的資料夾中,且該目錄與HTML頁面位於同一資料夾(Google建議這樣的編排,以利於SEO /索引目的),則應將其嵌入如下:

+ +
<img src="images/dinosaur.jpg">
+ +

像這樣.

+ +
+

提醒: 搜索引擎還會讀取圖片名稱,並將其納入SEO中。 因此您應該為圖片提供一個描述性的檔名。 例如 dinosaur.jpg 的命名方式會比 img835.png 更好。

+
+ +

你也可以用絕對路徑URL來嵌入圖片,例如

+ +
<img src="https://www.example.com/images/dinosaur.jpg">
+ +

但這麼做是沒有意義的,因為它只會使瀏覽器執行更多工作,瀏覽器需重複執行從DNS服務器中搜尋IP地址等等工作。您應將網站上的圖片與HTML存放在同一個伺服器上。

+ +
+

注意: 大多數圖像均受版權保護。 請勿在你的網站上隨意顯示圖片,除非:

+ + + +

侵犯版權是違法及不道德的。 此外,切勿將src屬性指向您未被授權的他人網站上的圖便。 這稱為“熱連結”。再次重申,竊取某人的頻寬是違法的,且這會減慢您網站的速度。此外當別人變更、移除或換上令人尷尬的內容時你將無法做出改變。

+
+ +

我們上面的程式碼將有以下結果:

+ +

A basic image of a dinosaur, embedded in a browser, with "Images in HTML" written above it

+ +
+

提醒: <img>和<video>之類的元素有時也稱為替換元素。 這是因為元素的內容和圖片大小是由外部(例如圖片或影音檔)所定義的,而不是由元素的內容定義。

+
+ +
+

提醒: 您可以從在Github上找到本節完成的示例(參見開源碼。)

+
+ +

替代性文字

+ +

我們下一個要看的屬性是alt。 它的功能算是圖片的文字描述,應用於因網路連接速度慢而無法看到/顯示圖片或需要長時間來跑圖等等情況。 例如,上面的程式碼我們可以像這樣修改:

+ +
<img src="images/dinosaur.jpg"
+     alt="The head and torso of a dinosaur skeleton;
+          it has a large head with long sharp teeth">
+ +

測試替代文字最簡單方法是故意拼錯檔名。 例如,如果我們的圖片名稱為dinosooooor.jpg,則瀏覽器將不會顯示該圖片,而是顯示alt文本:The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.

+ +

那麼,為什麼您會看到或需要替代文字? 它可以派上用場的原因有很多:

+ + + +

您應該在alt屬性中確切寫些什麼? 這取決於圖片為何而出現;也就是說,如果圖片不顯示,您將損失什麼:

+ + + +

本質上,關鍵是即使在看不見圖片的情況下也能提供相同的體驗。這樣可以確保所有使用者都不會丟失任何內容。嘗試在瀏覽器中關閉圖像,然後查看外觀。您很快就會意識到,如果看不到圖片,替代文字會很有幫助。

+ +
+

Note: For more information, see our guide to Text Alternatives.

+
+ +

寬與高

+ +

You can use the width and height attributes to specify the width and height of your image. You can find your image's width and height in a number of ways. For example on the Mac you can use Cmd + I to get the info display up for the image file. Returning to our example, we could do this:

+ +
<img src="images/dinosaur.jpg"
+     alt="The head and torso of a dinosaur skeleton;
+          it has a large head with long sharp teeth"
+     width="400"
+     height="341">
+ +

This doesn't result in much difference to the display, under normal circumstances. But if the image isn't being displayed, for example, the user has just navigated to the page, and the image hasn't yet loaded, you'll notice the browser is leaving a space for the image to appear in:

+ +

The Images in HTML title, with dinosaur alt text, displayed inside a large box that results from width and height settings

+ +

This is a good thing to do, resulting in the page loading quicker and more smoothly.

+ +

However, you shouldn't alter the size of your images using HTML attributes. If you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. The image may also end up looking distorted, if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.

+ +
+

Note: If you do need to alter an image's size, you should use CSS instead.

+
+ +

圖片標題

+ +

As with links, you can also add title attributes to images, to provide further supporting information if needed. In our example, we could do this:

+ +
<img src="images/dinosaur.jpg"
+     alt="The head and torso of a dinosaur skeleton;
+          it has a large head with long sharp teeth"
+     width="400"
+     height="341"
+     title="A T-Rex on display in the Manchester University Museum">
+ +

This gives us a tooltip on mouse hover, just like link titles:

+ +

The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum

+ +

However, this does not come recommended — title has a number of accessibility problems, mainly based around the fact that screen reader support is very unpredictable and most browsers won't show it unless you are hovering with a mouse (so e.g. no access to keyboard users). If you are interested in more information about this, read The Trials and Tribulations of the Title Attribute by Scott O'Hara.

+ +

It is better to include such supporting information in the main article text, rather than attached to the image.

+ +

實戰練習:嵌入圖片

+ +

It is now your turn to play! This active learning section will have you up and running with a simple embedding exercise. You are provided with a basic {{htmlelement("img")}} tag; we'd like you to embed the image located at the following URL:

+ +

https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

+ +

Earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.

+ +

We would also like you to:

+ + + +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

+ +

用圖文和圖文標註說明圖像

+ +

Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you from doing this:

+ +
<div class="figure">
+  <img src="images/dinosaur.jpg"
+       alt="The head and torso of a dinosaur skeleton;
+            it has a large head with long sharp teeth"
+       width="400"
+       height="341">
+
+  <p>A T-Rex on display in the Manchester University Museum.</p>
+</div>
+ +

This is ok. It contains the content you need, and is nicely stylable using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?

+ +

A better solution, is to use the HTML5 {{htmlelement("figure")}} and {{htmlelement("figcaption")}} elements. These are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. Our above example could be rewritten like this:

+ +
<figure>
+  <img src="images/dinosaur.jpg"
+       alt="The head and torso of a dinosaur skeleton;
+            it has a large head with long sharp teeth"
+       width="400"
+       height="341">
+
+  <figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>
+</figure>
+ +

The {{htmlelement("figcaption")}} element tells browsers, and assistive technology that the caption describes the other content of the {{htmlelement("figure")}} element.

+ +
+

Note: From an accessibility viewpoint, captions and {{htmlattrxref('alt','img')}} text have distinct roles. Captions benefit even people who can see the image, whereas {{htmlattrxref('alt','img')}} text provides the same functionality as an absent image. Therefore, captions and alt text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.

+
+ +

A figure doesn't have to be an image. It is an independent unit of content that:

+ + + +

A figure could be several images, a code snippet, audio, video, equations, a table, or something else.

+ +

實戰練習:建立圖文標註

+ +

In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:

+ +
    +
  1. Wrap it in a {{htmlelement("figure")}} element.
  2. +
  3. Copy the text out of the title attribute, remove the title attribute, and put the text inside a {{htmlelement("figcaption")}} element below the image.
  4. +
+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 350, "", "", "hide-codepen-jsfiddle") }}

+ +

CSS 背景圖片

+ +

您還可以使用CSS將圖像嵌入網頁(JavaScript也可以,但這完全是另一回事了)。 CSSbackground-image屬性和其他background- *屬性用於控制背景圖片的放置。 例如要將背景圖片放置在頁面的每個段落上,可以執行以下操作:

+ +
p {
+  background-image: url("images/dinosaur.jpg");
+}
+ +

這種嵌入圖片的方式比HTML圖像更容易定位和控制。 那麼,為什麼還要用HTML嵌入圖片呢? 如上所述,CSS背景圖像僅用於裝飾。 如果您只是想在頁面上添加一些漂亮的東西以增強視覺效果,那很好。 但是,此類圖像根本沒有語義。 它們與文字不同,對於螢幕閱讀器是不可見的,依此類推。 這裡需要的是HTML圖片!

+ +

總結來說,如果圖片在內容上具有含義,則應使用HTML圖像。 如果圖像純粹是裝飾性的,則應使用CSS背景圖片。

+ +
+

提醒: 在我們的CSS主題中,您將學到更多關於CSS背景圖片的知識。

+
+ +

試試看!

+ +

您已經來到了本文的末端,但是您還記得最重要的內容嗎? 在繼續往下之前,這裡有些測驗讓您驗證看看您是否都學會了 — 測驗:HTML圖像

+ +

總結

+ +

目前就是這樣啦。 我們已經詳細介紹了圖片和標題說明。 在下一篇文章中我們將進一步介紹,如何使用HTML將視頻和音頻嵌入在網頁中。

+ +

{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}

+ +

在這個主題中

+ + diff --git a/files/zh-tw/learn/html/multimedia_and_embedding/other_embedding_technologies/index.html b/files/zh-tw/learn/html/multimedia_and_embedding/other_embedding_technologies/index.html new file mode 100644 index 0000000000..a1996f2537 --- /dev/null +++ b/files/zh-tw/learn/html/multimedia_and_embedding/other_embedding_technologies/index.html @@ -0,0 +1,386 @@ +--- +title: 從物件到iframe - 其他嵌入技術 +slug: Learn/HTML/Multimedia_and_embedding/其他_嵌入_技術 +translation_of: Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding")}}
+ +

到現在為止,您應該真正掌握了將內容嵌入網頁的方法,包括圖片,影片和聲音。在這一點上,我們想採取一些橫向的措施,尋找一些元素,使您可以將各種內容類型嵌入到網頁中: {{htmlelement("iframe")}}, {{htmlelement("embed")}} 和 {{htmlelement("object")}} 元素。<iframe>用於嵌入其他網頁,另外兩個用於嵌入PDF,SVG甚至是Flash(這項技術正在淘汰,但您仍會半定期看到)。

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and the previous articles in this module.
Objective:To learn how to embed items into web pages using {{htmlelement("object")}}, {{htmlelement("embed")}}, and {{htmlelement("iframe")}}, like Flash movies and other webpages.
+ +

A short history of embedding

+ +

A long time ago on the Web, it was popular to use frames to create websites — small parts of a website stored in individual HTML pages. These were embedded in a master document called a frameset, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table. These were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds — especially noticeable with network connections being so slow back then. They did however have many problems, which far outweighed any positives as network speeds got faster, so you don't see them being used anymore.

+ +

A little while later (late 90s, early 2000s), plugin technologies became very popular, such as Java Applets and Flash — these allowed web developers to embed rich content into webpages such as videos and animations, which just weren't available through HTML alone. Embedding these technologies was achieved through elements like {{htmlelement("object")}}, and the lesser-used {{htmlelement("embed")}}, and they were very useful at the time. They have since fallen out of fashion due to many problems, including accessibility, security, file size, and more; these days most mobile devices don't support such plugins anymore, and desktop support is on the way out.

+ +

Finally, the {{htmlelement("iframe")}} element appeared (along with other ways of embedding content, such as {{htmlelement("canvas")}}, {{htmlelement("video")}}, etc.) This provides a way to embed an entire web document inside another one, as if it were an {{htmlelement("img")}} or other such element, and is used regularly today.

+ +

With the history lesson out of the way, let's move on and see how to use some of these.

+ +

Active learning: classic embedding uses

+ +

In this article we are going to jump straight into an active learning section, to immediately give you a real idea of just what embedding technologies are useful for. The online world is very familiar with Youtube, but many people don't know about some of the sharing facilities it has available. Let's look at how Youtube allows us to embed a video in any page we like using an {{htmlelement("iframe")}}.

+ +
    +
  1. First, go to Youtube and find a video you like.
  2. +
  3. Below the video, you'll find a Share button — select this to display the sharing options.
  4. +
  5. Select the Embed button and you'll be given some <iframe> code — copy this.
  6. +
  7. Insert it into the Input box below, and see what the result is in the Output.
  8. +
+ +

For bonus points, you could also try embedding a Google Map in the example:

+ +
    +
  1. Go to Google Maps and find a map you like.
  2. +
  3. Click on the "Hamburger Menu" (three horizontal lines) in the top left of the UI.
  4. +
  5. Select the Share or embed map option.
  6. +
  7. Select the Embed map option, which will give you some <iframe> code — copy this.
  8. +
  9. Insert it into the Input box below, and see what the result is in the Output.
  10. +
+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 600, "", "", "hide-codepen-jsfiddle") }}

+ +

Iframes in detail

+ +

So, that was easy and fun, right? {{htmlelement("iframe")}} elements are designed to allow you to embed other web documents into the current document. This is great for incorporating third-party content into your website that you might not have direct control over and don't want to have to implement your own version of — such as video from online video providers, commenting systems like Disqus, maps from online map providers, advertising banners, etc. The live editable examples you've been using through this course are implemented using <iframe>s.

+ +

There are some serious {{anch("Security concerns")}} to consider with <iframe>s, as we'll discuss below, but this doesn't mean that you shouldn't use them in your websites — it just requires some knowledge and careful thinking. Let's explore the code in a bit more detail. Say you wanted to include the MDN glossary on one of your web pages — you could try something like this:

+ +
<iframe src="https://developer.mozilla.org/en-US/docs/Glossary"
+        width="100%" height="500" frameborder="0"
+        allowfullscreen sandbox>
+  <p>
+    <a href="https://developer.mozilla.org/en-US/docs/Glossary">
+       Fallback link for browsers that don't support iframes
+    </a>
+  </p>
+</iframe>
+ +

This example includes the basic essentials needed to use an <iframe>:

+ +
+
{{htmlattrxref('allowfullscreen','iframe')}}
+
If set, the <iframe> is able to be placed in fullscreen mode using the Full Screen API (somewhat beyond scope for this article.)
+
{{htmlattrxref('frameborder','iframe')}}
+
If set to 1, this tells the browser to draw a border between this frame and other frames, which is the default behaviour. 0 removes the border. Using this isn't really recommended any more, as the same effect can be better achieved using {{cssxref('border')}}: none; in your {{Glossary('CSS')}}.
+
{{htmlattrxref('src','iframe')}}
+
This attribute, as with {{htmlelement("video")}}/{{htmlelement("img")}}, contains a path pointing to the URL of the document to be embedded.
+
{{htmlattrxref('width','iframe')}} and {{htmlattrxref('height','iframe')}}
+
These attributes specify the width and height you want the iframe to be.
+
Fallback content
+
In the same way as other similar elements like {{htmlelement("video")}}, you can include fallback content between the opening and closing <iframe></iframe> tags that will appear if the browser doesn't support the <iframe>. In this case, we have included a link to the page instead. It is unlikely that you'll come across any browser that doesn't support <iframe>s these days.
+
{{htmlattrxref('sandbox','iframe')}}
+
This attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section.
+
+ +
+

Note: In order to improve speed, it's a good idea to set the iframe's src attribute with JavaScript after the main content is done with loading. This makes your page usable sooner and decreases your official page load time (an important {{glossary("SEO")}} metric.)

+
+ +

Security concerns

+ +

Above we mentioned security concerns — let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to as you get more experienced and start considering using <iframe>s in your experiments and work. Also, there is no need to be scared and not use <iframe>s — you just need to be careful. Read on...

+ +

Browser makers and Web developers have learned the hard way that iframes are a common target (official term: attack vector) for bad people on the Web (often termed hackers, or more accurately, crackers) to attack if they are trying to maliciously modify your webpage, or trick people into doing something they don't want to do, such as reveal sensitive information like usernames and passwords. Because of this, spec engineers and browser developers have developed various security mechanisms for making <iframe>s more secure, and there are also best practices to consider — we'll cover some of these below.

+ +
+

{{interwiki('wikipedia','Clickjacking')}} is one kind of common iframe attack where hackers embed an invisible iframe into your document (or embed your document into their own malicious website) and use it to capture users' interactions. This is a common way to mislead users or steal sensitive data.

+
+ +

A quick example first though — try loading the previous example we showed above into your browser — you can find it live on Github (see the source code too.) You won't actually see anything displayed on the page, and if you look at the Console in the browser developer tools, you'll see a message telling you why. In Firefox, you'll get told Load denied by X-Frame-Options: https://developer.mozilla.org/en-US/docs/Glossary does not permit framing. This is because the developers that built MDN have included a setting on the server that serves the website pages to disallow them from being embedded inside <iframe>s (see {{anch("Configure CSP directives")}}, below.) This makes sense — an entire MDN page doesn't really make sense to be embedded in other pages unless you want to do something like embed them on your site and claim them as your own — or attempt to steal data via clickjacking, which are both really bad things to do. Plus if everybody started to do this, all the additional bandwidth would start to cost Mozilla a lot of money.

+ +

Only embed when necessary

+ +

Sometimes it makes sense to embed third-party content — like youtube videos and maps — but you can save yourself a lot of headaches if you only embed third-party content when completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven otherwise."

+ +
+

Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia Commons). Never display content on your webpage unless you own it or the owners have given you written, unequivocal permission. Penalties for copyright infringement are severe. Again, you can never be too cautious.

+ +

If the content is licensed, you must obey the license terms. For example, the content on MDN is licensed under CC-BY-SA. That means, you must credit us properly when you quote our content, even if you make substantial changes.

+
+ +

Use HTTPS

+ +

{{Glossary("HTTPS")}} is the encrypted version of {{Glossary("HTTP")}}. You should serve your websites using HTTPS whenever possible:

+ +
    +
  1. HTTPS reduces the chance that remote content has been tampered with in transit,
  2. +
  3. HTTPS prevents embedded content from accessing content in your parent document, and vice versa.
  4. +
+ +

Using HTTPS requires a security certificate, which can be expensive (although Let's Encrypt makes things easier) — if you can't get one, you may serve your parent document with HTTP. However, because of the second benefit of HTTPS above, no matter what the cost, you must never embed third-party content with HTTP. (In the best case scenario, your user's Web browser will give them a scary warning.) All reputable companies that make content available for embedding via an <iframe> will make it available via HTTPS — look at the URLs inside the <iframe> src attribute when you are embedding content from Google Maps or Youtube, for example.

+ +
+

Note: Github pages allow content to be served via HTTPS by default, so is useful for hosting content. If you are using different hosting and are not sure, ask your hosting provider about it.

+
+ +

Always use the sandbox attribute

+ +

You want to give attackers as little power as you can to do bad things on your website, therefore you should give embedded content only the permissions needed for doing its job. Of course, this applies to your own content, too. A container for code where it can be used appropriately — or for testing — but can't cause any harm to the rest of the codebase (either accidental or malicious) is called a sandbox.

+ +

Unsandboxed content can do way too much (executing JavaScript, submitting forms, popup windows, etc.) By default, you should impose all available restrictions by using the sandbox attribute with no parameters, as shown in our previous example.

+ +

If absolutely required, you can add permissions back one by one (inside the sandbox="" attribute value) — see the {{htmlattrxref('sandbox','iframe')}} reference entry for all the available options. One important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case, the embedded content could bypass the Same-origin policy that stops sites from executing scripts, and use JavaScript to turn off sandboxing altogether.

+ +
+

Note: Sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an iframe). If there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different {{glossary("domain")}} to your main site.

+
+ +

Configure CSP directives

+ +

{{Glossary("CSP")}} stands for content security policy and provides a set of HTTP Headers (metadata sent along with your web pages when they are served from a web server) designed to improve the security of your HTML document. When it comes to securing <iframe>s, you can configure your server to send an appropriate X-Frame-Options  header. This can prevent other websites from embedding your content in their web pages (which would enable {{interwiki('wikipedia','clickjacking')}} and a host of other attacks), which is exactly what the MDN developers have done, as we saw earlier on.

+ +
+

Note: You can read Frederik Braun's post On the X-Frame-Options Security Header for more background information on this topic. Obviously, it's rather out of scope for a full explanation in this article.

+
+ +

The <embed> and <object> elements

+ +

The {{htmlelement("embed")}} and {{htmlelement("object")}} elements serve a different function to {{htmlelement("iframe")}} — these elements are general purpose embedding tools for embedding multiple types of external content, which include plugin technologies like Java Applets and Flash, PDF (which can be shown in a browser with a PDF plugin), and even content like videos, SVG and images!

+ +
+

Note: A plugin, in this context, refers to software that provides access to content the browser cannot read natively.

+
+ +

However, you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see {{anch("The case against plugins")}}, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

+ +

If you find yourself needing to embed plugin content, this is the kind of information you'll need, at a minimum:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{htmlelement("embed")}}{{htmlelement("object")}}
{{glossary("URL")}} of the embedded content{{htmlattrxref('src','embed')}}{{htmlattrxref('data','object')}}
accurate {{glossary("MIME type", 'media type')}} of the embedded content{{htmlattrxref('type','embed')}}{{htmlattrxref('type','object')}}
height and width (in CSS pixels) of the box controlled by the plugin{{htmlattrxref('height','embed')}}
+ {{htmlattrxref('width','embed')}}
{{htmlattrxref('height','object')}}
+ {{htmlattrxref('width','object')}}
names and values, to feed the plugin as parametersad hoc attributes with those names and valuessingle-tag {{htmlelement("param")}} elements, contained within <object>
independent HTML content as fallback for an unavailable resourcenot supported (<noembed> is obsolete)contained within <object>, after <param> elements
+ +
+

Note: <object> requires a data attribute, a type attribute, or both. If you use both, you may also use the {{htmlattrxref('typemustmatch','object')}} attribute (only implemented in Firefox and Chrome, as of this writing). typemustmatch keeps the embedded file from running unless the type attribute provides the correct media type. typemustmatch can therefore confer significant security benefits when you're embedding content from a different {{glossary("origin")}} (it can keep attackers from running arbitrary scripts through the plugin).

+
+ +

Here's an example that uses the {{htmlelement("embed")}} element to embed a Flash movie (see this live on Github, and check the source code too):

+ +
<embed src="whoosh.swf" quality="medium"
+       bgcolor="#ffffff" width="550" height="400"
+       name="whoosh" align="middle" allowScriptAccess="sameDomain"
+       allowFullScreen="false" type="application/x-shockwave-flash"
+       pluginspage="http://www.macromedia.com/go/getflashplayer">
+ +

Pretty horrible, isn't it? The HTML generated by the Adobe Flash tool tended to be even worse, using an <object> element with an <embed> element embedded in it, to cover all bases (check out an example.) Flash was even used successfully as fallback content for HTML5 video, for a time, but this is increasingly being seen as not necessary.

+ +

Now let's look at an <object> example that embeds a PDF into a page (see the live example and the source code):

+ +
<object data="mypdf.pdf" type="application/pdf"
+        width="800" height="1200" typemustmatch>
+  <p>You don't have a PDF plugin, but you can
+    <a href="mypdf.pdf">download the PDF file.
+    </a>
+  </p>
+</object>
+ +

PDFs were a necessary stepping stone between paper and digital, but they pose many accessibility challenges and can be hard to read on small screens. They do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage.

+ +

The case against plugins

+ +

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.

+ + + +
+

Note: Due to its inherent issues and the lack of support for Flash, Adobe announced that they would stop supporting it at the end of 2020.  As of January 2020, most browsers block Flash content by default, and by December 31st of 2020, all browsers will have completly removed all Flash functionality. Any existing Flash content will be inaccessable after that date.

+
+ +

So what should you do? If you need interactivity, HTML and {{glossary("JavaScript")}} can readily get the job done for you with no need for Java applets or outdated ActiveX/BHO technology. Instead of relying on Adobe Flash, you should use HTML5 video for your media needs, SVG for vector graphics, and Canvas for complex images and animations. Peter Elst was already writing some years ago that Adobe Flash is rarely the right tool for the job. As for ActiveX, even Microsoft's {{glossary("Microsoft Edge","Edge")}} browser no longer supports it.

+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Multimedia and embedding.

+ +

Summary

+ +

The topic of embedding other content in web documents can quickly become very complex, so in this article, we've tried to introduce it in a simple, familiar way that will immediately seem relevant, while still hinting at some of the more advanced features of the involved technologies. To start with, you are unlikely to use embedding for much beyond including third-party content like maps and videos on your pages. As you become more experienced, however, you are likely to start finding more uses for them.

+ +

There are many other technologies that involve embedding external content besides the ones we discussed here. We saw some in earlier articles, such as {{htmlelement("video")}}, {{htmlelement("audio")}}, and {{htmlelement("img")}}, but there are others to discover, such as {{htmlelement("canvas")}} for JavaScript-generated 2D and 3D graphics, and {{SVGElement("svg")}} for embedding vector graphics. We'll look at SVG in the next article of the module.

+ +

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding")}}

+ +

In this module

+ + diff --git "a/files/zh-tw/learn/html/multimedia_and_embedding/\345\205\266\344\273\226_\345\265\214\345\205\245_\346\212\200\350\241\223/index.html" "b/files/zh-tw/learn/html/multimedia_and_embedding/\345\205\266\344\273\226_\345\265\214\345\205\245_\346\212\200\350\241\223/index.html" deleted file mode 100644 index a1996f2537..0000000000 --- "a/files/zh-tw/learn/html/multimedia_and_embedding/\345\205\266\344\273\226_\345\265\214\345\205\245_\346\212\200\350\241\223/index.html" +++ /dev/null @@ -1,386 +0,0 @@ ---- -title: 從物件到iframe - 其他嵌入技術 -slug: Learn/HTML/Multimedia_and_embedding/其他_嵌入_技術 -translation_of: Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding")}}
- -

到現在為止,您應該真正掌握了將內容嵌入網頁的方法,包括圖片,影片和聲音。在這一點上,我們想採取一些橫向的措施,尋找一些元素,使您可以將各種內容類型嵌入到網頁中: {{htmlelement("iframe")}}, {{htmlelement("embed")}} 和 {{htmlelement("object")}} 元素。<iframe>用於嵌入其他網頁,另外兩個用於嵌入PDF,SVG甚至是Flash(這項技術正在淘汰,但您仍會半定期看到)。

- - - - - - - - - - - - -
Prerequisites:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and the previous articles in this module.
Objective:To learn how to embed items into web pages using {{htmlelement("object")}}, {{htmlelement("embed")}}, and {{htmlelement("iframe")}}, like Flash movies and other webpages.
- -

A short history of embedding

- -

A long time ago on the Web, it was popular to use frames to create websites — small parts of a website stored in individual HTML pages. These were embedded in a master document called a frameset, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table. These were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds — especially noticeable with network connections being so slow back then. They did however have many problems, which far outweighed any positives as network speeds got faster, so you don't see them being used anymore.

- -

A little while later (late 90s, early 2000s), plugin technologies became very popular, such as Java Applets and Flash — these allowed web developers to embed rich content into webpages such as videos and animations, which just weren't available through HTML alone. Embedding these technologies was achieved through elements like {{htmlelement("object")}}, and the lesser-used {{htmlelement("embed")}}, and they were very useful at the time. They have since fallen out of fashion due to many problems, including accessibility, security, file size, and more; these days most mobile devices don't support such plugins anymore, and desktop support is on the way out.

- -

Finally, the {{htmlelement("iframe")}} element appeared (along with other ways of embedding content, such as {{htmlelement("canvas")}}, {{htmlelement("video")}}, etc.) This provides a way to embed an entire web document inside another one, as if it were an {{htmlelement("img")}} or other such element, and is used regularly today.

- -

With the history lesson out of the way, let's move on and see how to use some of these.

- -

Active learning: classic embedding uses

- -

In this article we are going to jump straight into an active learning section, to immediately give you a real idea of just what embedding technologies are useful for. The online world is very familiar with Youtube, but many people don't know about some of the sharing facilities it has available. Let's look at how Youtube allows us to embed a video in any page we like using an {{htmlelement("iframe")}}.

- -
    -
  1. First, go to Youtube and find a video you like.
  2. -
  3. Below the video, you'll find a Share button — select this to display the sharing options.
  4. -
  5. Select the Embed button and you'll be given some <iframe> code — copy this.
  6. -
  7. Insert it into the Input box below, and see what the result is in the Output.
  8. -
- -

For bonus points, you could also try embedding a Google Map in the example:

- -
    -
  1. Go to Google Maps and find a map you like.
  2. -
  3. Click on the "Hamburger Menu" (three horizontal lines) in the top left of the UI.
  4. -
  5. Select the Share or embed map option.
  6. -
  7. Select the Embed map option, which will give you some <iframe> code — copy this.
  8. -
  9. Insert it into the Input box below, and see what the result is in the Output.
  10. -
- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 600, "", "", "hide-codepen-jsfiddle") }}

- -

Iframes in detail

- -

So, that was easy and fun, right? {{htmlelement("iframe")}} elements are designed to allow you to embed other web documents into the current document. This is great for incorporating third-party content into your website that you might not have direct control over and don't want to have to implement your own version of — such as video from online video providers, commenting systems like Disqus, maps from online map providers, advertising banners, etc. The live editable examples you've been using through this course are implemented using <iframe>s.

- -

There are some serious {{anch("Security concerns")}} to consider with <iframe>s, as we'll discuss below, but this doesn't mean that you shouldn't use them in your websites — it just requires some knowledge and careful thinking. Let's explore the code in a bit more detail. Say you wanted to include the MDN glossary on one of your web pages — you could try something like this:

- -
<iframe src="https://developer.mozilla.org/en-US/docs/Glossary"
-        width="100%" height="500" frameborder="0"
-        allowfullscreen sandbox>
-  <p>
-    <a href="https://developer.mozilla.org/en-US/docs/Glossary">
-       Fallback link for browsers that don't support iframes
-    </a>
-  </p>
-</iframe>
- -

This example includes the basic essentials needed to use an <iframe>:

- -
-
{{htmlattrxref('allowfullscreen','iframe')}}
-
If set, the <iframe> is able to be placed in fullscreen mode using the Full Screen API (somewhat beyond scope for this article.)
-
{{htmlattrxref('frameborder','iframe')}}
-
If set to 1, this tells the browser to draw a border between this frame and other frames, which is the default behaviour. 0 removes the border. Using this isn't really recommended any more, as the same effect can be better achieved using {{cssxref('border')}}: none; in your {{Glossary('CSS')}}.
-
{{htmlattrxref('src','iframe')}}
-
This attribute, as with {{htmlelement("video")}}/{{htmlelement("img")}}, contains a path pointing to the URL of the document to be embedded.
-
{{htmlattrxref('width','iframe')}} and {{htmlattrxref('height','iframe')}}
-
These attributes specify the width and height you want the iframe to be.
-
Fallback content
-
In the same way as other similar elements like {{htmlelement("video")}}, you can include fallback content between the opening and closing <iframe></iframe> tags that will appear if the browser doesn't support the <iframe>. In this case, we have included a link to the page instead. It is unlikely that you'll come across any browser that doesn't support <iframe>s these days.
-
{{htmlattrxref('sandbox','iframe')}}
-
This attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section.
-
- -
-

Note: In order to improve speed, it's a good idea to set the iframe's src attribute with JavaScript after the main content is done with loading. This makes your page usable sooner and decreases your official page load time (an important {{glossary("SEO")}} metric.)

-
- -

Security concerns

- -

Above we mentioned security concerns — let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to as you get more experienced and start considering using <iframe>s in your experiments and work. Also, there is no need to be scared and not use <iframe>s — you just need to be careful. Read on...

- -

Browser makers and Web developers have learned the hard way that iframes are a common target (official term: attack vector) for bad people on the Web (often termed hackers, or more accurately, crackers) to attack if they are trying to maliciously modify your webpage, or trick people into doing something they don't want to do, such as reveal sensitive information like usernames and passwords. Because of this, spec engineers and browser developers have developed various security mechanisms for making <iframe>s more secure, and there are also best practices to consider — we'll cover some of these below.

- -
-

{{interwiki('wikipedia','Clickjacking')}} is one kind of common iframe attack where hackers embed an invisible iframe into your document (or embed your document into their own malicious website) and use it to capture users' interactions. This is a common way to mislead users or steal sensitive data.

-
- -

A quick example first though — try loading the previous example we showed above into your browser — you can find it live on Github (see the source code too.) You won't actually see anything displayed on the page, and if you look at the Console in the browser developer tools, you'll see a message telling you why. In Firefox, you'll get told Load denied by X-Frame-Options: https://developer.mozilla.org/en-US/docs/Glossary does not permit framing. This is because the developers that built MDN have included a setting on the server that serves the website pages to disallow them from being embedded inside <iframe>s (see {{anch("Configure CSP directives")}}, below.) This makes sense — an entire MDN page doesn't really make sense to be embedded in other pages unless you want to do something like embed them on your site and claim them as your own — or attempt to steal data via clickjacking, which are both really bad things to do. Plus if everybody started to do this, all the additional bandwidth would start to cost Mozilla a lot of money.

- -

Only embed when necessary

- -

Sometimes it makes sense to embed third-party content — like youtube videos and maps — but you can save yourself a lot of headaches if you only embed third-party content when completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven otherwise."

- -
-

Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia Commons). Never display content on your webpage unless you own it or the owners have given you written, unequivocal permission. Penalties for copyright infringement are severe. Again, you can never be too cautious.

- -

If the content is licensed, you must obey the license terms. For example, the content on MDN is licensed under CC-BY-SA. That means, you must credit us properly when you quote our content, even if you make substantial changes.

-
- -

Use HTTPS

- -

{{Glossary("HTTPS")}} is the encrypted version of {{Glossary("HTTP")}}. You should serve your websites using HTTPS whenever possible:

- -
    -
  1. HTTPS reduces the chance that remote content has been tampered with in transit,
  2. -
  3. HTTPS prevents embedded content from accessing content in your parent document, and vice versa.
  4. -
- -

Using HTTPS requires a security certificate, which can be expensive (although Let's Encrypt makes things easier) — if you can't get one, you may serve your parent document with HTTP. However, because of the second benefit of HTTPS above, no matter what the cost, you must never embed third-party content with HTTP. (In the best case scenario, your user's Web browser will give them a scary warning.) All reputable companies that make content available for embedding via an <iframe> will make it available via HTTPS — look at the URLs inside the <iframe> src attribute when you are embedding content from Google Maps or Youtube, for example.

- -
-

Note: Github pages allow content to be served via HTTPS by default, so is useful for hosting content. If you are using different hosting and are not sure, ask your hosting provider about it.

-
- -

Always use the sandbox attribute

- -

You want to give attackers as little power as you can to do bad things on your website, therefore you should give embedded content only the permissions needed for doing its job. Of course, this applies to your own content, too. A container for code where it can be used appropriately — or for testing — but can't cause any harm to the rest of the codebase (either accidental or malicious) is called a sandbox.

- -

Unsandboxed content can do way too much (executing JavaScript, submitting forms, popup windows, etc.) By default, you should impose all available restrictions by using the sandbox attribute with no parameters, as shown in our previous example.

- -

If absolutely required, you can add permissions back one by one (inside the sandbox="" attribute value) — see the {{htmlattrxref('sandbox','iframe')}} reference entry for all the available options. One important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case, the embedded content could bypass the Same-origin policy that stops sites from executing scripts, and use JavaScript to turn off sandboxing altogether.

- -
-

Note: Sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an iframe). If there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different {{glossary("domain")}} to your main site.

-
- -

Configure CSP directives

- -

{{Glossary("CSP")}} stands for content security policy and provides a set of HTTP Headers (metadata sent along with your web pages when they are served from a web server) designed to improve the security of your HTML document. When it comes to securing <iframe>s, you can configure your server to send an appropriate X-Frame-Options  header. This can prevent other websites from embedding your content in their web pages (which would enable {{interwiki('wikipedia','clickjacking')}} and a host of other attacks), which is exactly what the MDN developers have done, as we saw earlier on.

- -
-

Note: You can read Frederik Braun's post On the X-Frame-Options Security Header for more background information on this topic. Obviously, it's rather out of scope for a full explanation in this article.

-
- -

The <embed> and <object> elements

- -

The {{htmlelement("embed")}} and {{htmlelement("object")}} elements serve a different function to {{htmlelement("iframe")}} — these elements are general purpose embedding tools for embedding multiple types of external content, which include plugin technologies like Java Applets and Flash, PDF (which can be shown in a browser with a PDF plugin), and even content like videos, SVG and images!

- -
-

Note: A plugin, in this context, refers to software that provides access to content the browser cannot read natively.

-
- -

However, you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see {{anch("The case against plugins")}}, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

- -

If you find yourself needing to embed plugin content, this is the kind of information you'll need, at a minimum:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{{htmlelement("embed")}}{{htmlelement("object")}}
{{glossary("URL")}} of the embedded content{{htmlattrxref('src','embed')}}{{htmlattrxref('data','object')}}
accurate {{glossary("MIME type", 'media type')}} of the embedded content{{htmlattrxref('type','embed')}}{{htmlattrxref('type','object')}}
height and width (in CSS pixels) of the box controlled by the plugin{{htmlattrxref('height','embed')}}
- {{htmlattrxref('width','embed')}}
{{htmlattrxref('height','object')}}
- {{htmlattrxref('width','object')}}
names and values, to feed the plugin as parametersad hoc attributes with those names and valuessingle-tag {{htmlelement("param")}} elements, contained within <object>
independent HTML content as fallback for an unavailable resourcenot supported (<noembed> is obsolete)contained within <object>, after <param> elements
- -
-

Note: <object> requires a data attribute, a type attribute, or both. If you use both, you may also use the {{htmlattrxref('typemustmatch','object')}} attribute (only implemented in Firefox and Chrome, as of this writing). typemustmatch keeps the embedded file from running unless the type attribute provides the correct media type. typemustmatch can therefore confer significant security benefits when you're embedding content from a different {{glossary("origin")}} (it can keep attackers from running arbitrary scripts through the plugin).

-
- -

Here's an example that uses the {{htmlelement("embed")}} element to embed a Flash movie (see this live on Github, and check the source code too):

- -
<embed src="whoosh.swf" quality="medium"
-       bgcolor="#ffffff" width="550" height="400"
-       name="whoosh" align="middle" allowScriptAccess="sameDomain"
-       allowFullScreen="false" type="application/x-shockwave-flash"
-       pluginspage="http://www.macromedia.com/go/getflashplayer">
- -

Pretty horrible, isn't it? The HTML generated by the Adobe Flash tool tended to be even worse, using an <object> element with an <embed> element embedded in it, to cover all bases (check out an example.) Flash was even used successfully as fallback content for HTML5 video, for a time, but this is increasingly being seen as not necessary.

- -

Now let's look at an <object> example that embeds a PDF into a page (see the live example and the source code):

- -
<object data="mypdf.pdf" type="application/pdf"
-        width="800" height="1200" typemustmatch>
-  <p>You don't have a PDF plugin, but you can
-    <a href="mypdf.pdf">download the PDF file.
-    </a>
-  </p>
-</object>
- -

PDFs were a necessary stepping stone between paper and digital, but they pose many accessibility challenges and can be hard to read on small screens. They do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage.

- -

The case against plugins

- -

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.

- - - -
-

Note: Due to its inherent issues and the lack of support for Flash, Adobe announced that they would stop supporting it at the end of 2020.  As of January 2020, most browsers block Flash content by default, and by December 31st of 2020, all browsers will have completly removed all Flash functionality. Any existing Flash content will be inaccessable after that date.

-
- -

So what should you do? If you need interactivity, HTML and {{glossary("JavaScript")}} can readily get the job done for you with no need for Java applets or outdated ActiveX/BHO technology. Instead of relying on Adobe Flash, you should use HTML5 video for your media needs, SVG for vector graphics, and Canvas for complex images and animations. Peter Elst was already writing some years ago that Adobe Flash is rarely the right tool for the job. As for ActiveX, even Microsoft's {{glossary("Microsoft Edge","Edge")}} browser no longer supports it.

- -

Test your skills!

- -

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Multimedia and embedding.

- -

Summary

- -

The topic of embedding other content in web documents can quickly become very complex, so in this article, we've tried to introduce it in a simple, familiar way that will immediately seem relevant, while still hinting at some of the more advanced features of the involved technologies. To start with, you are unlikely to use embedding for much beyond including third-party content like maps and videos on your pages. As you become more experienced, however, you are likely to start finding more uses for them.

- -

There are many other technologies that involve embedding external content besides the ones we discussed here. We saw some in earlier articles, such as {{htmlelement("video")}}, {{htmlelement("audio")}}, and {{htmlelement("img")}}, but there are others to discover, such as {{htmlelement("canvas")}} for JavaScript-generated 2D and 3D graphics, and {{SVGElement("svg")}} for embedding vector graphics. We'll look at SVG in the next article of the module.

- -

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/html/tables/basics/index.html b/files/zh-tw/learn/html/tables/basics/index.html new file mode 100644 index 0000000000..03325afbce --- /dev/null +++ b/files/zh-tw/learn/html/tables/basics/index.html @@ -0,0 +1,568 @@ +--- +title: HTML表格的基礎 +slug: Learn/HTML/Tables/基礎 +translation_of: Learn/HTML/Tables/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +

這篇文章將帶你從列、格、標頭,以及將各格以數欄、數列的方式合併等基礎開始探索HTML表格。

+ + + + + + + + + + + + +
先備知識: +

HTML的基礎(見介紹HTML)

+
目標:對HTML表格有基本的認識
+ +

什麼是表格?

+ +

表格是一個由列和欄組成的結構化資料(tabular data)。表格能幫助你快速查看不同資料類型間的關聯值。例如人和年紀、一周當中的某天或是地方游泳池的時間表。

+ +

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

+ +

A swimming timetable showing a sample data table

+ +

表格在人類社會當中被廣泛使用且已經有很久的歷史,如下是美國1800年的人口普查紀錄表格。

+ +

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

+ +

這也難怪HTML的開創者要提供一個在網路建立和呈現表格化資料的方法。

+ +

表格是怎麼運作的呢?

+ +

表格是精確的,資訊可以透過列和欄位名稱之間的視覺關聯輕鬆呈現。觀察以下表格,利用列和欄目名稱找出有62個衛星的類木行星。

+ +

有關太陽系星球的資訊 (真實資料取自 Nasa's Planetary Fact Sheet - Metric. )

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名稱質量(1024kg)直徑 (km)密度(kg/m3)重力(m/s2)一天的長度(小時)和太陽的距離(106km)平均溫度 (°C)衛星的數目備註
陸地行星水星0.3304,87954273.74222.657.91670最接近太陽
金星4.8712,10452438.92802.0108.24640
地球5.9712,75655149.824.0149.6151我們的世界
火星0.6426,79239333.724.7227.9-652紅色星球
類木行星氣態巨行星木星1898142,984132623.19.9778.6-11067最大的星球
土星568120,5366879.010.71433.5-14062
冰質巨行星天王星86.851,11812718.717.22872.5-19527
海王星10249,528163811.016.14495.1-20014
矮行星冥王星0.01462,37020950.7153.35906.4-2255在2006年被從行星類別中除名,但這還些爭議
+ +

在正確執行之下,就連視障者都可以把表格資料詮釋為HTML格式的表格。一份成功的HTML表格就應該如此提升視障者的使用經驗。

+ +

表格樣式

+ +

你也可以在 GitHub 上看看實際範例 ! 而你也許會注意到那裡的表格似乎更容易閱讀。那是因為這裡的表格只有加上很少樣式,而GitHub上的版本卻應用上了更多明顯的CSS 。

+ +

需要弄清楚的一點是 : 要讓表格在網頁上有效呈現需要提供紮實的HTML架構和CSS樣式資訊,但將在這個模組中聚焦在HTML的部分。若想瞭解CSS的部分,可以在完成這部分閱讀之後造訪表格樣式設計的文章。

+ +

在這個單元裡我們將不會聚焦在CSS上,但是我們提供基本的CSS樣式表讓你做使用,這將會使你製作的表格比起毫無修飾的預設樣式更方便閱讀。你能在這找到樣式表,並且你也能找到一個適用於樣式表的HTML模版 — 他們能一起讓你有個好起點來實驗HTML表格。

+ +

當何時你不應該使用HTML表格?

+ +

HTML表格應該被使用在結構化資料(tabular data)上 — 這就是它們被設計的目的。
+ 不幸地是,許多人習慣使用HTML表格去排版他們的網頁,例如: 使用一列去當header,一列當做內容欄位,一列當作footer...等等,你能在我們的輔助學習單元裡的頁面輸出發現更多細節以及一個範例。它曾經被這麼使用是因為CSS過去在不同瀏覽器之間的支援程度十分可怕; 如今,已非常少在用表格做排版,但你仍然可能在網路的一些邊邊角角見到。

+ +

簡單來說,使用表格排版而非使用CSS排版技術是一件很糟的事情。
+ 下列是主要原因:

+ +
    +
  1. 表格排版會減少對視障使用者的輔助 : 視障者使用的螢幕閱讀器會翻譯存在於HTML網頁的標籤並對使用者念出內容。由於表格並不是正確的排版工具,並且標示方式遠複雜於CSS排版技術,所以螢幕閱讀器輸出的內容會使他們的使用者感到困惑。
  2. +
  3. 表格會產生標籤雜燴(tag soup): 就像上面提到的,表格排版通常會比一般適當的輸出技術包含更複雜的標籤結構。這會導致程式碼本身更難撰寫、維護及debug。
  4. +
  5. 表格不會自適應(automatically responsive): 當你使用合適的排版容器(像是{htmlelement("header")}, {{htmlelement("section")}}) 或是 {{htmlelement("div")}}),它們的寬度相對於父層預設為100%,而表格的預設大小是依據它們的內容物,所以當表格樣式要有效的在不同的裝置之間運行時,會需要做額外的測量調整。
  6. +
+ +

主動學習:建造你第一個表格

+ +

關於表格的理論我們已經談論夠了,所以,來深入實際的例子並建立一個簡單的表格吧!

+ +
    +
  1. 第一件事,在自己的電腦複製一份新的空白模板.html 以及 簡易表格.css 
  2. +
  3. 每一個表格裡的內容都是由這兩個標籤所組成:<table></table> 將這些放入你的HTML中的body。
  4. +
  5. 表格裡最小的容器是表格儲存格,由<td>元素所組成('td' 代表 'table data')。將下列的程式碼加入你的表格標籤之中: +
    <td>Hi, I'm your first cell.</td>
    +
  6. +
  7. 如果我們想要一個四格儲存格寬的列(row), 我們需要複製這些標籤三次。
    + 將你的表格內容更新成這樣: +
    <td>Hi, I'm your first cell.</td>
    +<td>I'm your second cell.</td>
    +<td>I'm your third cell.</td>
    +<td>I'm your fourth cell.</td>
    +
  8. +
+ +

就像你看到的,儲存格不會在各自的下方,它們彼此自動排列在同一列上。每個 <td> 元素會創造單個儲存格並且使它們據在同一行,我們新增的每一個儲存格都會使列更長。

+ +

要讓這個列停止增加並開始在下一列增加連續的儲存格的話,我們需要用 <tr> 元素 ('tr' 代表 'table row'),現在來探討一下:

+ +
    +
  1. 放置四個你已新增在 <tr> 標籤裡的儲存格, 像這樣: + +
    <tr>
    +  <td>Hi, I'm your first cell.</td>
    +  <td>I'm your second cell.</td>
    +  <td>I'm your third cell.</td>
    +  <td>I'm your fourth cell.</td>
    +</tr>
    +
  2. +
  3. 現在你已經製作了一列了,可以再繼續做一、二列 — 每個列都需要被額外的 <tr> 元素包裹住, 並且每個儲存格都須包含在一個 <td>  內
  4. +
+ +

表格應該會看起來像下面這樣:

+ + + + + + + + + + + + + + + + +
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
+ +
+

Note: 你也可以在GitHub 上看到 simple-table.html (see it live also).

+
+ +

用 <th> 加上標頭元素

+ +

現在,讓我們把注意力轉移到表格的標頭(table header) — 存在於一列或一欄開頭的特別儲存格並且定義了欄或列中內容的資料型態 (舉個例子, 看看這篇文章中第一個範例裡 的"Person" 和 "Age" 儲存格 )。
+ 為了說明為什麼它們很有用,請看下面的表格例子, 首先是程式碼:

+ +
<table>
+  <tr>
+    <td>&nbsp;</td>
+    <td>Knocky</td>
+    <td>Flor</td>
+    <td>Ella</td>
+    <td>Juan</td>
+  </tr>
+  <tr>
+    <td>Breed</td>
+    <td>Jack Russell</td>
+    <td>Poodle</td>
+    <td>Streetdog</td>
+    <td>Cocker Spaniel</td>
+  </tr>
+  <tr>
+    <td>Age</td>
+    <td>16</td>
+    <td>9</td>
+    <td>10</td>
+    <td>5</td>
+  </tr>
+  <tr>
+    <td>Owner</td>
+    <td>Mother-in-law</td>
+    <td>Me</td>
+    <td>Me</td>
+    <td>Sister-in-law</td>
+  </tr>
+  <tr>
+    <td>Eating Habits</td>
+    <td>Eats everyone's leftovers</td>
+    <td>Nibbles at food</td>
+    <td>Hearty eater</td>
+    <td>Will eat till he explodes</td>
+  </tr>
+</table>
+ +

這是實際渲染出的表格:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
+ +

這裡的問題在於,當你找到想知道的資料時,並不容易去找到資料之間對應的位置。如果欄跟列能有個明顯的標示,會比較好理解。

+ +

主動學習 : 表格標頭

+ +

讓我們來繼續改善這個表格吧!

+ +
    +
  1. 首先, 複製 dogs-table.html and minimal-table.css 檔案到你的電腦。
    + 這份HTML裡包含跟底下你看到的一樣的狗狗範例。
  2. +
  3. 為了在語意上和視覺上辨識表格的標頭,你可以使用 <th> 元素 ('th' 代表 'table header')。它的運作方式跟 <td> 完全相同,除了它表示的是標頭而非一般儲存格外。
    + 繼續修改你的HTML將所有外圍的 <td> 元素變成 <th> 元素。
  4. +
  5. 儲存你的HTML並在瀏覽器上執行,現在你應該可以看到標頭應有的樣子。
  6. +
+ +
+

Note: 你可以在GitHub上的dogs-table-fixed.html找到我們寫好的完整的範例(直接看看長怎樣).

+
+ +

標頭為什麼實用?

+ +

我們已經部分解答了這個問題 — 當有標頭清楚標示時,它能更簡單的使你找到資料並讓整體設計看起來更完整。

+ +
+

Note: 表格標頭有具備預設樣式 — 粗體並置中,即使你不加上你自己的表格樣式,他們仍然能被凸顯。

+
+ +

表格標頭還有一個額外的好處 — 伴隨著 作用域(scope) 屬性 (我們將會在下一個章節中學到),當要連結每個標頭而所有資料都在同一列或欄時,這能允許表格使用起來更無障礙。並且,螢幕閱讀器能一次性讀出完整一列或一欄的資料,這是非常實用的。

+ +

允許列或欄的儲存格合併

+ +

有時我們想要儲存格涵蓋複數的列或欄,來看看下列顯示常見動物名稱的簡單例子。在某些案例,我們想要將名字代表雄性或雌性顯示在動物名字旁邊,但有些不需要,這種情況下我們只想將動物名字橫跨整個表格。

+ +

初始架構會看起來像這樣:

+ +
<table>
+  <tr>
+    <th>Animals</th>
+  </tr>
+  <tr>
+    <th>Hippopotamus</th>
+  </tr>
+  <tr>
+    <th>Horse</th>
+    <td>Mare</td>
+  </tr>
+  <tr>
+    <td>Stallion</td>
+  </tr>
+  <tr>
+    <th>Crocodile</th>
+  </tr>
+  <tr>
+    <th>Chicken</th>
+    <td>Hen</td>
+  </tr>
+  <tr>
+    <td>Rooster</td>
+  </tr>
+</table>
+ +

但輸出的不如我們想要的樣子:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenHen
Rooster
+ +

我們需要一種方式讓"Animals", "Hippopotamus", 和 "Crocodile" 橫跨兩個欄位, 然後讓 "Horse" and "Chicken" 向下合併兩列儲存格。幸運地是,表格標頭和儲存格有 colspan 和 rowspan 屬性,可以讓我們這樣做。 兩者都接受無單位的數值等同於你想合併的列或欄的數量。舉例來說,colspan="2" 會讓這個儲存格合併兩欄。

+ +

來使用 colspan 和 rowspan 來改善這麼表格吧!

+ +
    +
  1. 首先,複製一份我們的 animals-table.html 和 minimal-table.css 檔案在你的電腦上。這個HTML包含跟上面同樣的動物範例。
  2. +
  3. 接著,使用 colspan 來讓 "Animals", "Hippopotamus", 和 "Crocodile" 合併橫跨兩個欄位。
  4. +
  5. 最後, 使用 rowspan 來讓 "Horse" and "Chicken" 合併橫跨兩列。
  6. +
  7. 儲存並在瀏覽器上檢視你改善後的程式碼。
  8. +
+ +
+

Note: 你可以在GitHub上的 animals-table-fixed.html 找到我們寫好的完整的範例 (see it live also).

+
+ + +
+ +

Providing common styling to columns

+ +

在我們繼續下去前,我們將要告訴你這節文章最後一個重點。HTML有一個一次定義一整欄樣式資訊的方法 —  <col>  <colgroup> 元素。These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

+ +
+

Note: Styling columns like this is limited to a few properties: border, background, width, and visibility. To set other properties you'll have to either style every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

+
+ +

Take the following simple example:

+ +
<table>
+  <tr>
+    <th>Data 1</th>
+    <th style="background-color: yellow">Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td style="background-color: yellow">Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td style="background-color: yellow">Jazz</td>
+  </tr>
+</table>
+ +

Which gives us the following result:

+ + + + + + + + + + + + + + + + +
Data 1Data 2
CalcuttaOrange
RobotsJazz
+ +

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

+ +
<table>
+  <colgroup>
+    <col>
+    <col style="background-color: yellow">
+  </colgroup>
+  <tr>
+    <th>Data 1</th>
+    <th>Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td>Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td>Jazz</td>
+  </tr>
+</table>
+ +

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

+ +

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

+ +
<colgroup>
+  <col style="background-color: yellow" span="2">
+</colgroup>
+ +

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

+ +

Active learning: colgroup and col

+ +

Now it's time to have a go yourself.

+ +

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

+ +

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

+ +

Recreate the table by following the steps below.

+ +
    +
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. +
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. +
  5. The first two columns need to be left unstyled.
  6. +
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. +
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. +
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. +
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. +
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. +
+ +

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

+ +

Summary

+ +

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

+ +
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +
+

In this module

+ + +
diff --git "a/files/zh-tw/learn/html/tables/\345\237\272\347\244\216/index.html" "b/files/zh-tw/learn/html/tables/\345\237\272\347\244\216/index.html" deleted file mode 100644 index 03325afbce..0000000000 --- "a/files/zh-tw/learn/html/tables/\345\237\272\347\244\216/index.html" +++ /dev/null @@ -1,568 +0,0 @@ ---- -title: HTML表格的基礎 -slug: Learn/HTML/Tables/基礎 -translation_of: Learn/HTML/Tables/Basics ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -

這篇文章將帶你從列、格、標頭,以及將各格以數欄、數列的方式合併等基礎開始探索HTML表格。

- - - - - - - - - - - - -
先備知識: -

HTML的基礎(見介紹HTML)

-
目標:對HTML表格有基本的認識
- -

什麼是表格?

- -

表格是一個由列和欄組成的結構化資料(tabular data)。表格能幫助你快速查看不同資料類型間的關聯值。例如人和年紀、一周當中的某天或是地方游泳池的時間表。

- -

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

- -

A swimming timetable showing a sample data table

- -

表格在人類社會當中被廣泛使用且已經有很久的歷史,如下是美國1800年的人口普查紀錄表格。

- -

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

- -

這也難怪HTML的開創者要提供一個在網路建立和呈現表格化資料的方法。

- -

表格是怎麼運作的呢?

- -

表格是精確的,資訊可以透過列和欄位名稱之間的視覺關聯輕鬆呈現。觀察以下表格,利用列和欄目名稱找出有62個衛星的類木行星。

- -

有關太陽系星球的資訊 (真實資料取自 Nasa's Planetary Fact Sheet - Metric. )

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
名稱質量(1024kg)直徑 (km)密度(kg/m3)重力(m/s2)一天的長度(小時)和太陽的距離(106km)平均溫度 (°C)衛星的數目備註
陸地行星水星0.3304,87954273.74222.657.91670最接近太陽
金星4.8712,10452438.92802.0108.24640
地球5.9712,75655149.824.0149.6151我們的世界
火星0.6426,79239333.724.7227.9-652紅色星球
類木行星氣態巨行星木星1898142,984132623.19.9778.6-11067最大的星球
土星568120,5366879.010.71433.5-14062
冰質巨行星天王星86.851,11812718.717.22872.5-19527
海王星10249,528163811.016.14495.1-20014
矮行星冥王星0.01462,37020950.7153.35906.4-2255在2006年被從行星類別中除名,但這還些爭議
- -

在正確執行之下,就連視障者都可以把表格資料詮釋為HTML格式的表格。一份成功的HTML表格就應該如此提升視障者的使用經驗。

- -

表格樣式

- -

你也可以在 GitHub 上看看實際範例 ! 而你也許會注意到那裡的表格似乎更容易閱讀。那是因為這裡的表格只有加上很少樣式,而GitHub上的版本卻應用上了更多明顯的CSS 。

- -

需要弄清楚的一點是 : 要讓表格在網頁上有效呈現需要提供紮實的HTML架構和CSS樣式資訊,但將在這個模組中聚焦在HTML的部分。若想瞭解CSS的部分,可以在完成這部分閱讀之後造訪表格樣式設計的文章。

- -

在這個單元裡我們將不會聚焦在CSS上,但是我們提供基本的CSS樣式表讓你做使用,這將會使你製作的表格比起毫無修飾的預設樣式更方便閱讀。你能在這找到樣式表,並且你也能找到一個適用於樣式表的HTML模版 — 他們能一起讓你有個好起點來實驗HTML表格。

- -

當何時你不應該使用HTML表格?

- -

HTML表格應該被使用在結構化資料(tabular data)上 — 這就是它們被設計的目的。
- 不幸地是,許多人習慣使用HTML表格去排版他們的網頁,例如: 使用一列去當header,一列當做內容欄位,一列當作footer...等等,你能在我們的輔助學習單元裡的頁面輸出發現更多細節以及一個範例。它曾經被這麼使用是因為CSS過去在不同瀏覽器之間的支援程度十分可怕; 如今,已非常少在用表格做排版,但你仍然可能在網路的一些邊邊角角見到。

- -

簡單來說,使用表格排版而非使用CSS排版技術是一件很糟的事情。
- 下列是主要原因:

- -
    -
  1. 表格排版會減少對視障使用者的輔助 : 視障者使用的螢幕閱讀器會翻譯存在於HTML網頁的標籤並對使用者念出內容。由於表格並不是正確的排版工具,並且標示方式遠複雜於CSS排版技術,所以螢幕閱讀器輸出的內容會使他們的使用者感到困惑。
  2. -
  3. 表格會產生標籤雜燴(tag soup): 就像上面提到的,表格排版通常會比一般適當的輸出技術包含更複雜的標籤結構。這會導致程式碼本身更難撰寫、維護及debug。
  4. -
  5. 表格不會自適應(automatically responsive): 當你使用合適的排版容器(像是{htmlelement("header")}, {{htmlelement("section")}}) 或是 {{htmlelement("div")}}),它們的寬度相對於父層預設為100%,而表格的預設大小是依據它們的內容物,所以當表格樣式要有效的在不同的裝置之間運行時,會需要做額外的測量調整。
  6. -
- -

主動學習:建造你第一個表格

- -

關於表格的理論我們已經談論夠了,所以,來深入實際的例子並建立一個簡單的表格吧!

- -
    -
  1. 第一件事,在自己的電腦複製一份新的空白模板.html 以及 簡易表格.css 
  2. -
  3. 每一個表格裡的內容都是由這兩個標籤所組成:<table></table> 將這些放入你的HTML中的body。
  4. -
  5. 表格裡最小的容器是表格儲存格,由<td>元素所組成('td' 代表 'table data')。將下列的程式碼加入你的表格標籤之中: -
    <td>Hi, I'm your first cell.</td>
    -
  6. -
  7. 如果我們想要一個四格儲存格寬的列(row), 我們需要複製這些標籤三次。
    - 將你的表格內容更新成這樣: -
    <td>Hi, I'm your first cell.</td>
    -<td>I'm your second cell.</td>
    -<td>I'm your third cell.</td>
    -<td>I'm your fourth cell.</td>
    -
  8. -
- -

就像你看到的,儲存格不會在各自的下方,它們彼此自動排列在同一列上。每個 <td> 元素會創造單個儲存格並且使它們據在同一行,我們新增的每一個儲存格都會使列更長。

- -

要讓這個列停止增加並開始在下一列增加連續的儲存格的話,我們需要用 <tr> 元素 ('tr' 代表 'table row'),現在來探討一下:

- -
    -
  1. 放置四個你已新增在 <tr> 標籤裡的儲存格, 像這樣: - -
    <tr>
    -  <td>Hi, I'm your first cell.</td>
    -  <td>I'm your second cell.</td>
    -  <td>I'm your third cell.</td>
    -  <td>I'm your fourth cell.</td>
    -</tr>
    -
  2. -
  3. 現在你已經製作了一列了,可以再繼續做一、二列 — 每個列都需要被額外的 <tr> 元素包裹住, 並且每個儲存格都須包含在一個 <td>  內
  4. -
- -

表格應該會看起來像下面這樣:

- - - - - - - - - - - - - - - - -
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
- -
-

Note: 你也可以在GitHub 上看到 simple-table.html (see it live also).

-
- -

用 <th> 加上標頭元素

- -

現在,讓我們把注意力轉移到表格的標頭(table header) — 存在於一列或一欄開頭的特別儲存格並且定義了欄或列中內容的資料型態 (舉個例子, 看看這篇文章中第一個範例裡 的"Person" 和 "Age" 儲存格 )。
- 為了說明為什麼它們很有用,請看下面的表格例子, 首先是程式碼:

- -
<table>
-  <tr>
-    <td>&nbsp;</td>
-    <td>Knocky</td>
-    <td>Flor</td>
-    <td>Ella</td>
-    <td>Juan</td>
-  </tr>
-  <tr>
-    <td>Breed</td>
-    <td>Jack Russell</td>
-    <td>Poodle</td>
-    <td>Streetdog</td>
-    <td>Cocker Spaniel</td>
-  </tr>
-  <tr>
-    <td>Age</td>
-    <td>16</td>
-    <td>9</td>
-    <td>10</td>
-    <td>5</td>
-  </tr>
-  <tr>
-    <td>Owner</td>
-    <td>Mother-in-law</td>
-    <td>Me</td>
-    <td>Me</td>
-    <td>Sister-in-law</td>
-  </tr>
-  <tr>
-    <td>Eating Habits</td>
-    <td>Eats everyone's leftovers</td>
-    <td>Nibbles at food</td>
-    <td>Hearty eater</td>
-    <td>Will eat till he explodes</td>
-  </tr>
-</table>
- -

這是實際渲染出的表格:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
- -

這裡的問題在於,當你找到想知道的資料時,並不容易去找到資料之間對應的位置。如果欄跟列能有個明顯的標示,會比較好理解。

- -

主動學習 : 表格標頭

- -

讓我們來繼續改善這個表格吧!

- -
    -
  1. 首先, 複製 dogs-table.html and minimal-table.css 檔案到你的電腦。
    - 這份HTML裡包含跟底下你看到的一樣的狗狗範例。
  2. -
  3. 為了在語意上和視覺上辨識表格的標頭,你可以使用 <th> 元素 ('th' 代表 'table header')。它的運作方式跟 <td> 完全相同,除了它表示的是標頭而非一般儲存格外。
    - 繼續修改你的HTML將所有外圍的 <td> 元素變成 <th> 元素。
  4. -
  5. 儲存你的HTML並在瀏覽器上執行,現在你應該可以看到標頭應有的樣子。
  6. -
- -
-

Note: 你可以在GitHub上的dogs-table-fixed.html找到我們寫好的完整的範例(直接看看長怎樣).

-
- -

標頭為什麼實用?

- -

我們已經部分解答了這個問題 — 當有標頭清楚標示時,它能更簡單的使你找到資料並讓整體設計看起來更完整。

- -
-

Note: 表格標頭有具備預設樣式 — 粗體並置中,即使你不加上你自己的表格樣式,他們仍然能被凸顯。

-
- -

表格標頭還有一個額外的好處 — 伴隨著 作用域(scope) 屬性 (我們將會在下一個章節中學到),當要連結每個標頭而所有資料都在同一列或欄時,這能允許表格使用起來更無障礙。並且,螢幕閱讀器能一次性讀出完整一列或一欄的資料,這是非常實用的。

- -

允許列或欄的儲存格合併

- -

有時我們想要儲存格涵蓋複數的列或欄,來看看下列顯示常見動物名稱的簡單例子。在某些案例,我們想要將名字代表雄性或雌性顯示在動物名字旁邊,但有些不需要,這種情況下我們只想將動物名字橫跨整個表格。

- -

初始架構會看起來像這樣:

- -
<table>
-  <tr>
-    <th>Animals</th>
-  </tr>
-  <tr>
-    <th>Hippopotamus</th>
-  </tr>
-  <tr>
-    <th>Horse</th>
-    <td>Mare</td>
-  </tr>
-  <tr>
-    <td>Stallion</td>
-  </tr>
-  <tr>
-    <th>Crocodile</th>
-  </tr>
-  <tr>
-    <th>Chicken</th>
-    <td>Hen</td>
-  </tr>
-  <tr>
-    <td>Rooster</td>
-  </tr>
-</table>
- -

但輸出的不如我們想要的樣子:

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenHen
Rooster
- -

我們需要一種方式讓"Animals", "Hippopotamus", 和 "Crocodile" 橫跨兩個欄位, 然後讓 "Horse" and "Chicken" 向下合併兩列儲存格。幸運地是,表格標頭和儲存格有 colspan 和 rowspan 屬性,可以讓我們這樣做。 兩者都接受無單位的數值等同於你想合併的列或欄的數量。舉例來說,colspan="2" 會讓這個儲存格合併兩欄。

- -

來使用 colspan 和 rowspan 來改善這麼表格吧!

- -
    -
  1. 首先,複製一份我們的 animals-table.html 和 minimal-table.css 檔案在你的電腦上。這個HTML包含跟上面同樣的動物範例。
  2. -
  3. 接著,使用 colspan 來讓 "Animals", "Hippopotamus", 和 "Crocodile" 合併橫跨兩個欄位。
  4. -
  5. 最後, 使用 rowspan 來讓 "Horse" and "Chicken" 合併橫跨兩列。
  6. -
  7. 儲存並在瀏覽器上檢視你改善後的程式碼。
  8. -
- -
-

Note: 你可以在GitHub上的 animals-table-fixed.html 找到我們寫好的完整的範例 (see it live also).

-
- - -
- -

Providing common styling to columns

- -

在我們繼續下去前,我們將要告訴你這節文章最後一個重點。HTML有一個一次定義一整欄樣式資訊的方法 —  <col>  <colgroup> 元素。These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

- -
-

Note: Styling columns like this is limited to a few properties: border, background, width, and visibility. To set other properties you'll have to either style every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

-
- -

Take the following simple example:

- -
<table>
-  <tr>
-    <th>Data 1</th>
-    <th style="background-color: yellow">Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td style="background-color: yellow">Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td style="background-color: yellow">Jazz</td>
-  </tr>
-</table>
- -

Which gives us the following result:

- - - - - - - - - - - - - - - - -
Data 1Data 2
CalcuttaOrange
RobotsJazz
- -

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

- -
<table>
-  <colgroup>
-    <col>
-    <col style="background-color: yellow">
-  </colgroup>
-  <tr>
-    <th>Data 1</th>
-    <th>Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td>Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td>Jazz</td>
-  </tr>
-</table>
- -

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

- -

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

- -
<colgroup>
-  <col style="background-color: yellow" span="2">
-</colgroup>
- -

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

- -

Active learning: colgroup and col

- -

Now it's time to have a go yourself.

- -

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

- -

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

- -

Recreate the table by following the steps below.

- -
    -
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. -
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. -
  5. The first two columns need to be left unstyled.
  6. -
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. -
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. -
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. -
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. -
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. -
- -

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

- -

Summary

- -

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

- -
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -
-

In this module

- - -
diff --git a/files/zh-tw/learn/javascript/building_blocks/events/index.html b/files/zh-tw/learn/javascript/building_blocks/events/index.html new file mode 100644 index 0000000000..102e9cd314 --- /dev/null +++ b/files/zh-tw/learn/javascript/building_blocks/events/index.html @@ -0,0 +1,85 @@ +--- +title: Event attributes +slug: Web/Guide/HTML/Event_attributes +translation_of: >- + Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don%27t_use_these +translation_of_original: Web/Guide/HTML/Event_attributes +--- +

每一個 HTML 元素都可以放置事件屬性,以藉此於事件發生時能執行 JavaScripte 程式。事件屬性的名稱都有一個前綴「on」,例如當使用者點選元素時要執行指定的 JavaScript,可以使用 onclick 屬性並把要執行的 JavaScript 當成屬性值。

+ +

In the JavaScript code executed in response to the event, this is bound to the HTML element and the {{domxref("Event")}} object can be reached using the event variable in the scope of the attribute.

+ +
+

Warning: These attributes should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the {{domxref("Window")}} object, polluting the global namespace.

+
+ +

While these attributes can at times be attractively easy to use, you should avoid using them. Instead, use the {{domxref("EventTarget.addEventListener()")}} function to add a listener for the event.

+ +

Event attributes can be blocked by using Content Security Policy which if used, blocks all inline scripts unless the 'unsafe-inline' keyword is used.

+ +

Example using event attributes

+ +

This example appends text to an element each time time the {{HTMLElement("div")}} is clicked.

+ +
+

Note: This is an example of how not to do things, using one of these attributes.

+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>Event Attribute Example</title>
+    <script>
+      function doSomething() {
+        document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>";
+      }
+    </script>
+  </head>
+  <body>
+    <div onclick="doSomething();">Click me!</div>
+    <div id="thanks"></div>
+  </body>
+</html>
+
+ +

Try this example below:

+ +

{{ EmbedLiveSample('Example_using_event_attributes', '', '', '') }}

+ +

Example using event listeners

+ +

Instead, you should use {{domxref("EventTarget.addEventListener()")}}, as shown here:

+ +
<!doctype html>
+<html>
+  <head>
+    <title>Event Attribute Example</title>
+    <script>
+      function doSomething() {
+        document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>";
+      }
+
+      // Called when the page is done loading; this is where we do any setup we need,
+      // such as creating event listeners for the elements in the page.
+
+      function setup() {
+        document.getElementById("click").addEventListener("click", doSomething, true);
+      }
+
+      // Install an event handler on the window to receive the "load" event, which
+      // indicates that the document has finished loading into the window.
+
+      window.addEventListener("load", setup, true);
+    </script>
+  </head>
+  <body>
+    <div id="click">Click me!</div>
+    <div id="thanks"></div>
+  </body>
+</html>
+ +

You can see this in action below:

+ +

{{ EmbedLiveSample('Example_using_event_listeners', '', '', '') }}

+ + diff --git a/files/zh-tw/learn/performance/multimedia/index.html b/files/zh-tw/learn/performance/multimedia/index.html new file mode 100644 index 0000000000..cbd3d8e23a --- /dev/null +++ b/files/zh-tw/learn/performance/multimedia/index.html @@ -0,0 +1,130 @@ +--- +title: '多媒體: 圖像跟影片' +slug: Learn/Performance/多媒體 +translation_of: Learn/Performance/Multimedia +--- +

媒體,換句話說就是圖像跟影片,平均占了網站超過70%的下載流量。以下載的效能來考慮的話,減少媒體數量和檔案大小是一個簡單可以實現的目標。 這篇文章聚焦在優化圖像跟影片來改善網站的效能。

+ +
+

這是一篇進階的在 web 上優化多媒體的介紹,包含基本的原則還有技巧,想了更多的話,可以看  https://images.guide

+
+ +

為什麼要優化你的多媒體

+ +

對於平均的網站, 51% 的頻寬消耗來自圖像, 而影像則是 25%,所以我們可以說處理和優化你的多媒體是很重要的。

+ +

你必須考慮流量的使用. 很多的人都是使用流量有限制的上網方案, 或是用多少付多少的上網方案,也就是根據用了多少 MB 來付費。這樣的問題不是只發生在新興國家的市場. 在 2018 年, 英國仍有 24% 在使用「用多少付多少」的方案

+ +

你還需要考慮記憶體的問題,因為許多移動設備的 RAM 都有限。有一件很重要的事你必須要記住,下載的圖像是被儲存在記憶體裡的。

+ +

優化圖像傳送

+ +

儘管是頻寬的最大消耗者,但因為圖像是非同步載入的,所以訪問者可以在下載的同時看到頁面。因此,它們對感知性能的影響遠低於許多人的預期。 然而,圖像在內容中很常被使用,因此,重要的應該是讓訪問者盡快地看到它們,以獲得良好的體驗。

+ +

載入策略

+ +

對於大多數網站來說,最大改進之一是將不在視窗裡的圖像做 lazy-loading ,而不是在初始頁面載入時就全部下載下來,不管訪問者是否之後會往下滾動查看它們。 許多 JavaScript 函式庫都可以為你實現這個功能,例如說 lazysize,並且瀏覽器的供應商也正在著手原生的 lazyload 屬性,然而目前還處於實驗階段。

+ +

除了載入圖像的子集之外,接下來您還應該研究一下圖像本身的格式:

+ + + +

最佳格式

+ +

這非常值得用一個章節來介紹。因為為圖像選擇正確的格式可能很棘手。格式通常取決於圖像的用途:

+ + + +

優先在不需要移動卷軸就能看到的網頁區域使用 Progressive JPEG 的原因是因為它們會逐漸地進行渲染(因此得名),這意味著用戶可以先看到低解析度的版本,然後再逐漸地變得清晰。而不是從頂部一行一行的以最高解析度來載入圖像,或甚至只有在完全下載好後才顯示。

+ +

控制下載圖像的優先級別(和順序)

+ +

將最重要的圖像更早地呈現在訪問者面前,可以改善感知性能。

+ +

第一件要確認的事情是,你的前景圖像標籤 <img /> 跟你定義在 CSS 裡 background-image 的背景圖像 — 前景圖像比背景圖像被賦予更高的優先級別。

+ +

其次,通過採用優先級別提示,你可以在圖像標籤中添加importance 屬性來進一步控制優先級別。輪播是一個在圖像上使用優先級別提示的例子,它的第一個圖像的優先級高於其他的圖像。

+ +

渲染策略

+ +

由於圖像是非同步載入的,並且會在第一次渲染後繼續載入,因此,如果在載入之前未定義尺寸的話,則可能會導致頁面內容的重新編排。比如說,當圖像載入時,文字內容可能會被擠壓到下面。所以, 很重要的是,定義 width 跟 height 或是新的 intrinsicsize 屬性。

+ +

對於任何的背景圖像,設置 background-color 的值非常重要,因為在圖像下載之前,它能讓上面的內容是能夠被閱讀的。

+ +

優化影像傳送

+ +

為了確保您不會將不必要的大文件發送給用戶,最好 壓縮所有你要傳輸的影像優化<source> 順序, 設定 autoplay移除靜音影像的聲音, 優化影像預載, 還有 考慮串流 這部影像。

+ +

壓縮所有影像

+ +

大多數的影像壓縮工作都包含,比較影像裡的相鄰幀,並刪除原始幀和後續幀中相同的細節。你想同時壓縮影像並將其匯出為多種影像格式, 包含 WebM,MPEG-4/H.264,以及 Ogg/Theora.

+ +

你用來創建影像的軟體可能包含優化檔案大小的功能。如果沒有的話,那麼可以考慮幾種線上工具,像是之後篇章會討論的 FFmpeg,他可以協助編碼,解碼,轉換,以及呈現其他神奇的功能。

+ +

優化 <source> 順序

+ +

從最小到最大來排序影像的來源。例如說,給定三個壓縮影像,分別為 10 MB,12MB,以及13MB, 把最小的擺在第一個,最大的擺在最後一格。

+ +
<video width="400" height="300" controls="controls">
+  <!-- WebM: 10 MB -->
+  <source src="video.webm" type="video/webm" />
+  <!-- MPEG-4/H.264: 12 MB -->
+  <source src="video.mp4" type="video/mp4" />
+  <!-- Ogg/Theora: 13 MB -->
+  <source src="video.ogv" type="video/ogv" />
+</video>
+ +

就順序的角度來說,瀏覽器會下載它看到的第一個影像來源,因此先讓他載入一個較小的影像。就"最小"的角度來說,要確認你的壓縮影響仍然看起來不會太糟。有幾個演算法可能會讓你的影像看起來像是個會動的 gif 。雖然 128 Kb 的影像可能在用戶體驗上會比 10 MB 的影像好,可是把看起來像是 gif 粒狀的影像放在內容後面,也可能會對你的品牌產生負面影響。

+ +

查看 CanIUse.com 來確認現今瀏覽器對於影像以及不同媒體格式的支持。  

+ +

影像自動播放

+ +

為了確保循環播放背景影像,你需要向影像標籤裡添加多個屬性: autoplay, muted, 以及 playsinline.

+ +
<video autoplay="" loop="" muted="true" playsinline="" src="backgroundvideo.mp4">
+ +

雖然屬性 loop 和 autoplay 在對於影像的循環跟自動播放很合理,可是 muted 屬性在行動裝置的瀏覽器裡是必須添加的。

+ +

Playsinline 在行動裝置裡的 Safari 是必須的,他讓影像可以在不需要全螢幕的模式下被播放。

+ +

移除靜音影像的聲音

+ +

如果你有一個 hero-video 或是其他靜音影片, 請將聲音從影像中移除。 

+ +
<video autoplay="" loop="" muted="true" playsinline="" id="hero-video">
+  <source src="banner_video.webm"
+          type='video/webm; codecs="vp8, vorbis"'>
+  <source src="web_banner.mp4" type="video/mp4">
+</video>
+ +

這段 hero-video 代碼, 常出現在許多研討會網站以及公司的主頁, 它是個包括自動播放,循環播放和靜音的影像。它不包含任何控制選單,因此無法收聽聲音。通常它是沒有聲音的,但仍然存在音軌,因此它仍會消耗頻寬。然而,我們沒有理由將頻寬分給靜音影像的聲音。移除聲音可以節省 20% 的頻寬。這代表,如果你的影像是 10 MB,則節省了 2 MB。

+ +

根據您的影像創作軟體,你也許可以在匯出和壓縮過程中刪除聲音。 如果沒有,那麼有一個免費的工具 FFmpeg ,可以使用以下指令來為你完成此任務

+ +
ffmpeg -i original.mp4 -an -c:v copy audioFreeVersion.mp4
+ +

FFmpeg 稱自己為"用於記錄,轉換和串流音頻和影像的完整,跨平台解決方案"。

+ +

影像預載

+ +

preload 屬性具有3個可用選項:auto|metadata|none。預設選項是 metadata.

+ +

將選項更改為 auto 會告訴瀏覽器自動下載整個影像。僅有在極有可能播放時才應該執行此操作,否則會浪費大量的頻寬。

+ +

preload="metadata" 最多可讓 3% 的影像在頁面加載時被下載。 然後對於較大的影像來說,這可能或是大量的頻寬。

+ +

preload="none" 不會在播放之前下載任何的影像。 這會延遲影像的啟動時間,但能夠為播放可能性較低的影像保存大量的頻寬。

+ +

考慮串流

+ +

串流影像讓適當的影像大小和頻寬 (根據網路速度) 被傳遞給用戶。 就像使用響應式圖像一樣,正確大小的影像將被傳遞到瀏覽器,從而確保用戶的快速影像啟動、低緩衝以及優化的播放。

diff --git "a/files/zh-tw/learn/performance/\345\244\232\345\252\222\351\253\224/index.html" "b/files/zh-tw/learn/performance/\345\244\232\345\252\222\351\253\224/index.html" deleted file mode 100644 index cbd3d8e23a..0000000000 --- "a/files/zh-tw/learn/performance/\345\244\232\345\252\222\351\253\224/index.html" +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: '多媒體: 圖像跟影片' -slug: Learn/Performance/多媒體 -translation_of: Learn/Performance/Multimedia ---- -

媒體,換句話說就是圖像跟影片,平均占了網站超過70%的下載流量。以下載的效能來考慮的話,減少媒體數量和檔案大小是一個簡單可以實現的目標。 這篇文章聚焦在優化圖像跟影片來改善網站的效能。

- -
-

這是一篇進階的在 web 上優化多媒體的介紹,包含基本的原則還有技巧,想了更多的話,可以看  https://images.guide

-
- -

為什麼要優化你的多媒體

- -

對於平均的網站, 51% 的頻寬消耗來自圖像, 而影像則是 25%,所以我們可以說處理和優化你的多媒體是很重要的。

- -

你必須考慮流量的使用. 很多的人都是使用流量有限制的上網方案, 或是用多少付多少的上網方案,也就是根據用了多少 MB 來付費。這樣的問題不是只發生在新興國家的市場. 在 2018 年, 英國仍有 24% 在使用「用多少付多少」的方案

- -

你還需要考慮記憶體的問題,因為許多移動設備的 RAM 都有限。有一件很重要的事你必須要記住,下載的圖像是被儲存在記憶體裡的。

- -

優化圖像傳送

- -

儘管是頻寬的最大消耗者,但因為圖像是非同步載入的,所以訪問者可以在下載的同時看到頁面。因此,它們對感知性能的影響遠低於許多人的預期。 然而,圖像在內容中很常被使用,因此,重要的應該是讓訪問者盡快地看到它們,以獲得良好的體驗。

- -

載入策略

- -

對於大多數網站來說,最大改進之一是將不在視窗裡的圖像做 lazy-loading ,而不是在初始頁面載入時就全部下載下來,不管訪問者是否之後會往下滾動查看它們。 許多 JavaScript 函式庫都可以為你實現這個功能,例如說 lazysize,並且瀏覽器的供應商也正在著手原生的 lazyload 屬性,然而目前還處於實驗階段。

- -

除了載入圖像的子集之外,接下來您還應該研究一下圖像本身的格式:

- - - -

最佳格式

- -

這非常值得用一個章節來介紹。因為為圖像選擇正確的格式可能很棘手。格式通常取決於圖像的用途:

- - - -

優先在不需要移動卷軸就能看到的網頁區域使用 Progressive JPEG 的原因是因為它們會逐漸地進行渲染(因此得名),這意味著用戶可以先看到低解析度的版本,然後再逐漸地變得清晰。而不是從頂部一行一行的以最高解析度來載入圖像,或甚至只有在完全下載好後才顯示。

- -

控制下載圖像的優先級別(和順序)

- -

將最重要的圖像更早地呈現在訪問者面前,可以改善感知性能。

- -

第一件要確認的事情是,你的前景圖像標籤 <img /> 跟你定義在 CSS 裡 background-image 的背景圖像 — 前景圖像比背景圖像被賦予更高的優先級別。

- -

其次,通過採用優先級別提示,你可以在圖像標籤中添加importance 屬性來進一步控制優先級別。輪播是一個在圖像上使用優先級別提示的例子,它的第一個圖像的優先級高於其他的圖像。

- -

渲染策略

- -

由於圖像是非同步載入的,並且會在第一次渲染後繼續載入,因此,如果在載入之前未定義尺寸的話,則可能會導致頁面內容的重新編排。比如說,當圖像載入時,文字內容可能會被擠壓到下面。所以, 很重要的是,定義 width 跟 height 或是新的 intrinsicsize 屬性。

- -

對於任何的背景圖像,設置 background-color 的值非常重要,因為在圖像下載之前,它能讓上面的內容是能夠被閱讀的。

- -

優化影像傳送

- -

為了確保您不會將不必要的大文件發送給用戶,最好 壓縮所有你要傳輸的影像優化<source> 順序, 設定 autoplay移除靜音影像的聲音, 優化影像預載, 還有 考慮串流 這部影像。

- -

壓縮所有影像

- -

大多數的影像壓縮工作都包含,比較影像裡的相鄰幀,並刪除原始幀和後續幀中相同的細節。你想同時壓縮影像並將其匯出為多種影像格式, 包含 WebM,MPEG-4/H.264,以及 Ogg/Theora.

- -

你用來創建影像的軟體可能包含優化檔案大小的功能。如果沒有的話,那麼可以考慮幾種線上工具,像是之後篇章會討論的 FFmpeg,他可以協助編碼,解碼,轉換,以及呈現其他神奇的功能。

- -

優化 <source> 順序

- -

從最小到最大來排序影像的來源。例如說,給定三個壓縮影像,分別為 10 MB,12MB,以及13MB, 把最小的擺在第一個,最大的擺在最後一格。

- -
<video width="400" height="300" controls="controls">
-  <!-- WebM: 10 MB -->
-  <source src="video.webm" type="video/webm" />
-  <!-- MPEG-4/H.264: 12 MB -->
-  <source src="video.mp4" type="video/mp4" />
-  <!-- Ogg/Theora: 13 MB -->
-  <source src="video.ogv" type="video/ogv" />
-</video>
- -

就順序的角度來說,瀏覽器會下載它看到的第一個影像來源,因此先讓他載入一個較小的影像。就"最小"的角度來說,要確認你的壓縮影響仍然看起來不會太糟。有幾個演算法可能會讓你的影像看起來像是個會動的 gif 。雖然 128 Kb 的影像可能在用戶體驗上會比 10 MB 的影像好,可是把看起來像是 gif 粒狀的影像放在內容後面,也可能會對你的品牌產生負面影響。

- -

查看 CanIUse.com 來確認現今瀏覽器對於影像以及不同媒體格式的支持。  

- -

影像自動播放

- -

為了確保循環播放背景影像,你需要向影像標籤裡添加多個屬性: autoplay, muted, 以及 playsinline.

- -
<video autoplay="" loop="" muted="true" playsinline="" src="backgroundvideo.mp4">
- -

雖然屬性 loop 和 autoplay 在對於影像的循環跟自動播放很合理,可是 muted 屬性在行動裝置的瀏覽器裡是必須添加的。

- -

Playsinline 在行動裝置裡的 Safari 是必須的,他讓影像可以在不需要全螢幕的模式下被播放。

- -

移除靜音影像的聲音

- -

如果你有一個 hero-video 或是其他靜音影片, 請將聲音從影像中移除。 

- -
<video autoplay="" loop="" muted="true" playsinline="" id="hero-video">
-  <source src="banner_video.webm"
-          type='video/webm; codecs="vp8, vorbis"'>
-  <source src="web_banner.mp4" type="video/mp4">
-</video>
- -

這段 hero-video 代碼, 常出現在許多研討會網站以及公司的主頁, 它是個包括自動播放,循環播放和靜音的影像。它不包含任何控制選單,因此無法收聽聲音。通常它是沒有聲音的,但仍然存在音軌,因此它仍會消耗頻寬。然而,我們沒有理由將頻寬分給靜音影像的聲音。移除聲音可以節省 20% 的頻寬。這代表,如果你的影像是 10 MB,則節省了 2 MB。

- -

根據您的影像創作軟體,你也許可以在匯出和壓縮過程中刪除聲音。 如果沒有,那麼有一個免費的工具 FFmpeg ,可以使用以下指令來為你完成此任務

- -
ffmpeg -i original.mp4 -an -c:v copy audioFreeVersion.mp4
- -

FFmpeg 稱自己為"用於記錄,轉換和串流音頻和影像的完整,跨平台解決方案"。

- -

影像預載

- -

preload 屬性具有3個可用選項:auto|metadata|none。預設選項是 metadata.

- -

將選項更改為 auto 會告訴瀏覽器自動下載整個影像。僅有在極有可能播放時才應該執行此操作,否則會浪費大量的頻寬。

- -

preload="metadata" 最多可讓 3% 的影像在頁面加載時被下載。 然後對於較大的影像來說,這可能或是大量的頻寬。

- -

preload="none" 不會在播放之前下載任何的影像。 這會延遲影像的啟動時間,但能夠為播放可能性較低的影像保存大量的頻寬。

- -

考慮串流

- -

串流影像讓適當的影像大小和頻寬 (根據網路速度) 被傳遞給用戶。 就像使用響應式圖像一樣,正確大小的影像將被傳遞到瀏覽器,從而確保用戶的快速影像啟動、低緩衝以及優化的播放。

diff --git a/files/zh-tw/learn/server-side/first_steps/introduction/index.html b/files/zh-tw/learn/server-side/first_steps/introduction/index.html new file mode 100644 index 0000000000..a0919697ee --- /dev/null +++ b/files/zh-tw/learn/server-side/first_steps/introduction/index.html @@ -0,0 +1,225 @@ +--- +title: 伺服器端的介紹 +slug: Learn/Server-side/First_steps/介紹 +translation_of: Learn/Server-side/First_steps/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}
+ +

歡迎來到MDN伺服器端程式設計的初學者課程 !在第一篇文章中,我們會用較為抽象的角度來探討 server-side programming,並且為你解答「這是什麼?」「這個和用戶端的程式有什麼不同?」以及「這個有什麼用?」 。在讀完這篇文章後,你將能明白如何透過 server-side coding 來為你的網站增添力量。

+ + + + + + + + + + + + +
先決條件:基本電腦知識、對網路伺服器有基本了解。
目標:認識伺服器端的程式設計、它可以做什麼、它和用戶端的程式有什麼不一樣?
+ +

大多數的大型網站使用伺服器端程式(server-side code)來動態地顯示各種所需的資料,普遍的做法為從伺服端的資料庫中取出資料,並送至用戶端,再透過一些 code 來顯示它們(例如:HTML 與 JavaScript)。

+ +

也許,使用伺服器端程式的最大好處是為不同的瀏覽者量身打造網頁內容。動態網站根據使用者的偏好設定及興趣提供更為相關的內容,也可以儲存個人設定及資訊讓網站更易於使用 — 例如重複使用已儲存的信用卡資料來使付款流程更為順暢。

+ +

它也能讓網站透過信件或其他方式來和使用者互動,如發送通知與更新。這一切的一切都讓網站更能牢牢抓住使用者的心。

+ +

何謂伺服器端網站程式開發?

+ +

網頁瀏覽器使用超文本傳輸協定(HyperText Transfer Protocol, {{glossary("HTTP")}})與網頁伺服器(web servers)溝通。當您點選網頁上的連結、送出表單,或者執行搜尋,一段 HTTP 請求request)會由您的瀏覽器送至目標伺服器。

+ +

該請求(request)包含一個用來指定受影響資源的 URL、一個定義行為的請求方法(例如對資源進行get、delete或post)與當進行HTTP POST方法時可能包含編碼於URL參數中的額外資訊(經由一段查詢字串送出的各個鍵值對),或是在關聯的{{glossary("Cookie", "cookies")}}中。

+ +

網頁伺服器等待用戶端的請求訊息、獲得後處理它們,並以一個HTTP回應response)訊息回覆至網頁瀏覽器。該回應包含一個狀態訊息說明本次請求是否達成(例如:"HTTP/1.1 200 OK"表示成功)。

+ +

成功對應於一個請求的回應主體(response body)應包含請求的資源(例如:一份新的HTML頁面或一張圖片等),這些可能將被用來顯示在網頁瀏覽器中。

+ +

靜態網站

+ +

以下的靜態網站(static site)圖展示一個基本的網頁伺服器架構,其中靜態網站意謂當無論何時有個特定資源的請求,伺服器始終回傳相同的硬編碼內容(hard-coded content)。當一個使用者想要引導到一個網頁時,瀏覽器送出的HTTP "GET" 請求指的就是該資源的URL。

+ +

此伺服器從它的檔案系統取回被請求的文件,並回傳一個包含此文件以及成功狀態碼(通常為200 OK)的HTTP回應。若檔案因某些原因無法被取回,則回傳一個錯誤狀態(參見 用戶端錯誤回應 與 伺服器端錯誤回應)。

+ +

A simplified diagram of a static web server.

+ +

動態網站

+ +

一個動態網站的回應內容是當需要時動態產生的。在一個動態網站的HTML網頁通常是經由資料庫取得並插入資料至HTML範本的佔位符(placeholders)中而創造出來(相較於靜態網站,這對於儲存大量內容而言,這是一種相當有效率的做法)。 

+ +

一個動態網站可以根據使用者或已存偏好設定提供的URL資訊回傳不同的資料,也可以以其他的作用方式呈現回應(例如:發送通知)。

+ +

用來支援一個動態網站的大部分的程式碼必須在伺服器執行。建立程式碼的方式稱為"伺服端程式設計(server-side programming)"或"後端腳本(back-end scripting)"。

+ +

下圖為動態網站dynamic website)的基本架構。如同先前的圖說,瀏覽器發送HTTP請求至伺服器,接著伺服器處理請求後,回傳合適的HTTP回應。

+ +

對於靜態資源的請求處理方式如同靜態網站的方式(靜態資源為任何不會改變的檔案 — 通常為CSS、JavaScript、圖片、預產生的PDF檔案等)。 

+ +

A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.

+ +

對於動態資源的請求方式則為轉送(2)至伺服端程式碼(如圖中的網頁應用程式 Web Application)。對於"動態請求",伺服器解釋該請求、從資料庫讀取所需資訊(3)、與HTML範本結合取得的資料(4),最後送回一個包含已產生HTML的回應(5,6)。

+ +
+

伺服端與用戶端程式設計是相同的嗎?

+
+ +

讓我們把注意力集中在伺服端與用戶端的程式設計吧!在以下的每個案例中,程式碼完全不一樣:

+ + + +

執行在瀏覽器的程式碼被稱為用戶端程式碼client-side code),它主要用來改善一個渲染的網頁外觀與行為。這包含選取與設定UI元件樣式、建立佈局、導覽、表格驗證等。相對的,伺服端網站程式設計大量涉及要回傳哪些內容給瀏覽器做為對請求的回應。伺服端程式碼處理驗證已提交的資料與請求、使用資料庫儲存及取得資料,和按需求發送正確的資料給用戶等任務。

+ +

用戶端程式碼以HTMLCSSJavaScript撰寫 — 它執行在網頁瀏覽器內,並且僅有或無訪問底層的作業系統(包含對檔案系統的有限存取)。

+ +

網頁開發者不能控制使用者可能使用何種瀏覽器來檢視一個網站 — 瀏覽器與用戶端程式有著不同層度的相容性,並且用戶端程式的挑戰之一是如何妥善地處理瀏覽器支援的差異。

+ +

伺服端程式碼可以為任何程式語言 — 例如有名的伺服端網頁語言包括PHP、Python、Ruby、C#與NodeJS(JavaScript)。該伺服端程式碼擁有完整的作業系統存取權限,而且開發者能夠選擇他們想要的程式語言(以及特定版本)。

+ +

開發者們通常使用網頁框架web frameworks)撰寫程式碼。網頁框架為功能函式、物件、規則與其他程式碼的集合,旨在解決常見問題、加速開發並簡化在特定域中面臨到的不同類型的任務。

+ +

再者,儘管用戶端與伺服端程式碼都使用框架,但會因為非常不同的域,而使得框架也不同。用戶端網頁框架簡化佈局與呈現的任務,而伺服端網頁框架則提供大量"通用"的網頁伺服器功能,否則你可能必須要自己實現(例如:對sessions的支援、對使用者認證的支援、簡易資料庫存取、樣板庫等)。

+ +
+

Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI.

+ +

In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools.

+
+ +
+

在伺服端,你能做什麼?

+ +

伺服端程式設計是非常有用的,因為它讓我們有效地遞送替單個使用者量身訂做的資訊,從而創造更棒的使用者體驗。

+
+ +

如Amazon這樣的公司使用伺服端程式設計來建構產品搜尋結果、根據顧客偏好與過往購物習慣提供針對性的產品建議、簡化購物過程等。

+ +

銀行使用伺服端程式設計來儲存帳號資訊,並讓已授權用戶檢視與進行交易。其他服務如Facebook、Twitter、Instagram與Wikipedia使用伺服端程式設計來突顯、分享與控制使用者存取到感興趣的內容。

+ +

一些常見的伺服端程式設計使用案例與效益列舉如下。您將會注意到這當中會有些重疊的部分!

+ +

高效率資訊儲存與遞送

+ +

想像一下,在Amazon可以找到多少產品,或者說在Facebook上有多少文章?對各個產品或文章建立各別的靜態網頁完全是不切實際的。

+ +

伺服端程式設計反而是可以讓我們將資訊儲存至資料庫,並且動態建構及回傳HTML與其他型態的檔案(例如:PDF、圖片等)。它也可以藉由合適的用戶端網頁框架(利用這個方式可以降低在伺服器的處理負擔,亦減少需要被送出的大量資料)僅回傳資料({{glossary("JSON")}}、{{glossary("XML")}}等)來進行畫面渲染。

+ +

伺服器並不侷限於從資料庫發送資訊,還可以回傳軟體工具的結果或是來自通訊服務的資料。這些內容甚至可以針對到收到它的用戶裝置類型。

+ +

由於資訊存在於資料庫中,它可以輕易地與其他商業系統進行分享與更新(例如:當產品在線上或在店家中售完,店家可能會更新該產品的庫存資料庫)。

+ +
+

Note: Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information:

+ +
    +
  1. Go to Amazon or some other e-commerce site.
  2. +
  3. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 
  4. +
  5. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database.
  6. +
+ +

For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place.

+
+ +

客製化的使用者體驗

+ +

伺服器能保存及使用關於用戶的資訊,來提供一個方便且量身訂做的使用者體驗。例如,許多網站儲存信用卡資料讓這些資料無須再重新輸入。網站如Google Maps能使用已儲存或目前位置來提供導航資訊與搜尋或旅行歷史紀錄,以便於搜尋結果中突顯在地店家。

+ +

一個使用者習慣更深層的分析,可以使用在預測他的興趣以及更進一步客製回應與提醒,例如在地圖中提供你可能想去看得過去遊歷過的或是熱門的地點列表。

+ +
+

Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others.

+ +

Google search results are optimized based on previous searches.

+ +
    +
  1.  Go to Google search.
  2. +
  3.  Search for "football".
  4. +
  5.  Now try typing "favourite" in the search box and observe the autocomplete search predictions.
  6. +
+ +

Coincidence? Nada!

+
+ +

控制內容存取

+ +

伺服器端程式設計允許網站限制僅能由已授權的使用者存取,並提供資訊給那些只被允許觀看的使用者。

+ +

真實世界案例包括:

+ + + +
+

Note: Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change?

+
+ +

儲存session/state資訊

+ +

伺服器端程式設計允許開發者利用sessions — 基本上,就是一個機制讓伺服器儲存目前的使用者資訊,並且基於這些資訊發送不同的回應。

+ +

例如,這允許網站了解一個使用者先前已登入過,以及將訂購歷史紀錄在他們的電子郵件中顯示連結,或者也許會儲存一個基本的遊戲狀態,讓使用者能再次回到網站的同時,拿回他們留在網站的資訊。

+ +
+

Note: Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies.

+
+ +

提醒與溝通

+ +

伺服器能透過網站本身或經由電子郵件、SMS、即時通訊、影像或其他通訊服務,發送提醒訊息給一般或特定使用者。

+ +

一些範例包括:

+ + + +
+

Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account.

+
+ +

資料分析

+ +

一個網站可能會收集很多包括使用者的資料:他們所搜尋的、他們所買的、他們所推薦的、他們在每個網頁停留的時間。伺服器端程式設計能根據資料分析以完善回應。

+ +

例如,Amazon與Google都根據過往搜尋(與購買)紀錄來廣告產品。

+ +
+

Note: If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts.

+ +

Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits!

+
+ +

總結

+ +

恭喜,你已經到達關於伺服器端程式設計的第一篇文章的結尾。 

+ +

現在你已經學到伺服器端程式碼運作於網頁伺服器,他的主要任務是控制哪些資訊要發送給使用者(而用戶端程式碼主要掌握資料的結構與呈現給使用者)。

+ +

你也應該了解這是很有用的,當你身為伺服器端開發者時,因為它允許我們創建有效散播客製訊息與有些你可能會去做的好點子給單個使用者的網站。

+ +

最後,你應該了解伺服器端程式碼可以用很多種程式語言來撰寫,以及你應該使用網頁框架來讓整個程序變得更簡便。 

+ +

在未來的文章,我們將協助你選擇最佳的網頁框架,做為你的第一個網站;接著,我們將帶你更詳細了解主要的用戶端-伺服端的互動。

+ +

{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}

+ +

In this module

+ + diff --git "a/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" "b/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" deleted file mode 100644 index a0919697ee..0000000000 --- "a/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: 伺服器端的介紹 -slug: Learn/Server-side/First_steps/介紹 -translation_of: Learn/Server-side/First_steps/Introduction ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}
- -

歡迎來到MDN伺服器端程式設計的初學者課程 !在第一篇文章中,我們會用較為抽象的角度來探討 server-side programming,並且為你解答「這是什麼?」「這個和用戶端的程式有什麼不同?」以及「這個有什麼用?」 。在讀完這篇文章後,你將能明白如何透過 server-side coding 來為你的網站增添力量。

- - - - - - - - - - - - -
先決條件:基本電腦知識、對網路伺服器有基本了解。
目標:認識伺服器端的程式設計、它可以做什麼、它和用戶端的程式有什麼不一樣?
- -

大多數的大型網站使用伺服器端程式(server-side code)來動態地顯示各種所需的資料,普遍的做法為從伺服端的資料庫中取出資料,並送至用戶端,再透過一些 code 來顯示它們(例如:HTML 與 JavaScript)。

- -

也許,使用伺服器端程式的最大好處是為不同的瀏覽者量身打造網頁內容。動態網站根據使用者的偏好設定及興趣提供更為相關的內容,也可以儲存個人設定及資訊讓網站更易於使用 — 例如重複使用已儲存的信用卡資料來使付款流程更為順暢。

- -

它也能讓網站透過信件或其他方式來和使用者互動,如發送通知與更新。這一切的一切都讓網站更能牢牢抓住使用者的心。

- -

何謂伺服器端網站程式開發?

- -

網頁瀏覽器使用超文本傳輸協定(HyperText Transfer Protocol, {{glossary("HTTP")}})與網頁伺服器(web servers)溝通。當您點選網頁上的連結、送出表單,或者執行搜尋,一段 HTTP 請求request)會由您的瀏覽器送至目標伺服器。

- -

該請求(request)包含一個用來指定受影響資源的 URL、一個定義行為的請求方法(例如對資源進行get、delete或post)與當進行HTTP POST方法時可能包含編碼於URL參數中的額外資訊(經由一段查詢字串送出的各個鍵值對),或是在關聯的{{glossary("Cookie", "cookies")}}中。

- -

網頁伺服器等待用戶端的請求訊息、獲得後處理它們,並以一個HTTP回應response)訊息回覆至網頁瀏覽器。該回應包含一個狀態訊息說明本次請求是否達成(例如:"HTTP/1.1 200 OK"表示成功)。

- -

成功對應於一個請求的回應主體(response body)應包含請求的資源(例如:一份新的HTML頁面或一張圖片等),這些可能將被用來顯示在網頁瀏覽器中。

- -

靜態網站

- -

以下的靜態網站(static site)圖展示一個基本的網頁伺服器架構,其中靜態網站意謂當無論何時有個特定資源的請求,伺服器始終回傳相同的硬編碼內容(hard-coded content)。當一個使用者想要引導到一個網頁時,瀏覽器送出的HTTP "GET" 請求指的就是該資源的URL。

- -

此伺服器從它的檔案系統取回被請求的文件,並回傳一個包含此文件以及成功狀態碼(通常為200 OK)的HTTP回應。若檔案因某些原因無法被取回,則回傳一個錯誤狀態(參見 用戶端錯誤回應 與 伺服器端錯誤回應)。

- -

A simplified diagram of a static web server.

- -

動態網站

- -

一個動態網站的回應內容是當需要時動態產生的。在一個動態網站的HTML網頁通常是經由資料庫取得並插入資料至HTML範本的佔位符(placeholders)中而創造出來(相較於靜態網站,這對於儲存大量內容而言,這是一種相當有效率的做法)。 

- -

一個動態網站可以根據使用者或已存偏好設定提供的URL資訊回傳不同的資料,也可以以其他的作用方式呈現回應(例如:發送通知)。

- -

用來支援一個動態網站的大部分的程式碼必須在伺服器執行。建立程式碼的方式稱為"伺服端程式設計(server-side programming)"或"後端腳本(back-end scripting)"。

- -

下圖為動態網站dynamic website)的基本架構。如同先前的圖說,瀏覽器發送HTTP請求至伺服器,接著伺服器處理請求後,回傳合適的HTTP回應。

- -

對於靜態資源的請求處理方式如同靜態網站的方式(靜態資源為任何不會改變的檔案 — 通常為CSS、JavaScript、圖片、預產生的PDF檔案等)。 

- -

A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.

- -

對於動態資源的請求方式則為轉送(2)至伺服端程式碼(如圖中的網頁應用程式 Web Application)。對於"動態請求",伺服器解釋該請求、從資料庫讀取所需資訊(3)、與HTML範本結合取得的資料(4),最後送回一個包含已產生HTML的回應(5,6)。

- -
-

伺服端與用戶端程式設計是相同的嗎?

-
- -

讓我們把注意力集中在伺服端與用戶端的程式設計吧!在以下的每個案例中,程式碼完全不一樣:

- - - -

執行在瀏覽器的程式碼被稱為用戶端程式碼client-side code),它主要用來改善一個渲染的網頁外觀與行為。這包含選取與設定UI元件樣式、建立佈局、導覽、表格驗證等。相對的,伺服端網站程式設計大量涉及要回傳哪些內容給瀏覽器做為對請求的回應。伺服端程式碼處理驗證已提交的資料與請求、使用資料庫儲存及取得資料,和按需求發送正確的資料給用戶等任務。

- -

用戶端程式碼以HTMLCSSJavaScript撰寫 — 它執行在網頁瀏覽器內,並且僅有或無訪問底層的作業系統(包含對檔案系統的有限存取)。

- -

網頁開發者不能控制使用者可能使用何種瀏覽器來檢視一個網站 — 瀏覽器與用戶端程式有著不同層度的相容性,並且用戶端程式的挑戰之一是如何妥善地處理瀏覽器支援的差異。

- -

伺服端程式碼可以為任何程式語言 — 例如有名的伺服端網頁語言包括PHP、Python、Ruby、C#與NodeJS(JavaScript)。該伺服端程式碼擁有完整的作業系統存取權限,而且開發者能夠選擇他們想要的程式語言(以及特定版本)。

- -

開發者們通常使用網頁框架web frameworks)撰寫程式碼。網頁框架為功能函式、物件、規則與其他程式碼的集合,旨在解決常見問題、加速開發並簡化在特定域中面臨到的不同類型的任務。

- -

再者,儘管用戶端與伺服端程式碼都使用框架,但會因為非常不同的域,而使得框架也不同。用戶端網頁框架簡化佈局與呈現的任務,而伺服端網頁框架則提供大量"通用"的網頁伺服器功能,否則你可能必須要自己實現(例如:對sessions的支援、對使用者認證的支援、簡易資料庫存取、樣板庫等)。

- -
-

Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI.

- -

In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools.

-
- -
-

在伺服端,你能做什麼?

- -

伺服端程式設計是非常有用的,因為它讓我們有效地遞送替單個使用者量身訂做的資訊,從而創造更棒的使用者體驗。

-
- -

如Amazon這樣的公司使用伺服端程式設計來建構產品搜尋結果、根據顧客偏好與過往購物習慣提供針對性的產品建議、簡化購物過程等。

- -

銀行使用伺服端程式設計來儲存帳號資訊,並讓已授權用戶檢視與進行交易。其他服務如Facebook、Twitter、Instagram與Wikipedia使用伺服端程式設計來突顯、分享與控制使用者存取到感興趣的內容。

- -

一些常見的伺服端程式設計使用案例與效益列舉如下。您將會注意到這當中會有些重疊的部分!

- -

高效率資訊儲存與遞送

- -

想像一下,在Amazon可以找到多少產品,或者說在Facebook上有多少文章?對各個產品或文章建立各別的靜態網頁完全是不切實際的。

- -

伺服端程式設計反而是可以讓我們將資訊儲存至資料庫,並且動態建構及回傳HTML與其他型態的檔案(例如:PDF、圖片等)。它也可以藉由合適的用戶端網頁框架(利用這個方式可以降低在伺服器的處理負擔,亦減少需要被送出的大量資料)僅回傳資料({{glossary("JSON")}}、{{glossary("XML")}}等)來進行畫面渲染。

- -

伺服器並不侷限於從資料庫發送資訊,還可以回傳軟體工具的結果或是來自通訊服務的資料。這些內容甚至可以針對到收到它的用戶裝置類型。

- -

由於資訊存在於資料庫中,它可以輕易地與其他商業系統進行分享與更新(例如:當產品在線上或在店家中售完,店家可能會更新該產品的庫存資料庫)。

- -
-

Note: Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information:

- -
    -
  1. Go to Amazon or some other e-commerce site.
  2. -
  3. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 
  4. -
  5. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database.
  6. -
- -

For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place.

-
- -

客製化的使用者體驗

- -

伺服器能保存及使用關於用戶的資訊,來提供一個方便且量身訂做的使用者體驗。例如,許多網站儲存信用卡資料讓這些資料無須再重新輸入。網站如Google Maps能使用已儲存或目前位置來提供導航資訊與搜尋或旅行歷史紀錄,以便於搜尋結果中突顯在地店家。

- -

一個使用者習慣更深層的分析,可以使用在預測他的興趣以及更進一步客製回應與提醒,例如在地圖中提供你可能想去看得過去遊歷過的或是熱門的地點列表。

- -
-

Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others.

- -

Google search results are optimized based on previous searches.

- -
    -
  1.  Go to Google search.
  2. -
  3.  Search for "football".
  4. -
  5.  Now try typing "favourite" in the search box and observe the autocomplete search predictions.
  6. -
- -

Coincidence? Nada!

-
- -

控制內容存取

- -

伺服器端程式設計允許網站限制僅能由已授權的使用者存取,並提供資訊給那些只被允許觀看的使用者。

- -

真實世界案例包括:

- - - -
-

Note: Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change?

-
- -

儲存session/state資訊

- -

伺服器端程式設計允許開發者利用sessions — 基本上,就是一個機制讓伺服器儲存目前的使用者資訊,並且基於這些資訊發送不同的回應。

- -

例如,這允許網站了解一個使用者先前已登入過,以及將訂購歷史紀錄在他們的電子郵件中顯示連結,或者也許會儲存一個基本的遊戲狀態,讓使用者能再次回到網站的同時,拿回他們留在網站的資訊。

- -
-

Note: Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies.

-
- -

提醒與溝通

- -

伺服器能透過網站本身或經由電子郵件、SMS、即時通訊、影像或其他通訊服務,發送提醒訊息給一般或特定使用者。

- -

一些範例包括:

- - - -
-

Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account.

-
- -

資料分析

- -

一個網站可能會收集很多包括使用者的資料:他們所搜尋的、他們所買的、他們所推薦的、他們在每個網頁停留的時間。伺服器端程式設計能根據資料分析以完善回應。

- -

例如,Amazon與Google都根據過往搜尋(與購買)紀錄來廣告產品。

- -
-

Note: If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts.

- -

Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits!

-
- -

總結

- -

恭喜,你已經到達關於伺服器端程式設計的第一篇文章的結尾。 

- -

現在你已經學到伺服器端程式碼運作於網頁伺服器,他的主要任務是控制哪些資訊要發送給使用者(而用戶端程式碼主要掌握資料的結構與呈現給使用者)。

- -

你也應該了解這是很有用的,當你身為伺服器端開發者時,因為它允許我們創建有效散播客製訊息與有些你可能會去做的好點子給單個使用者的網站。

- -

最後,你應該了解伺服器端程式碼可以用很多種程式語言來撰寫,以及你應該使用網頁框架來讓整個程序變得更簡便。 

- -

在未來的文章,我們將協助你選擇最佳的網頁框架,做為你的第一個網站;接著,我們將帶你更詳細了解主要的用戶端-伺服端的互動。

- -

{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}

- -

In this module

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