From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../forms/how_to_structure_an_html_form/index.html | 315 +++++++ files/zh-tw/learn/html/forms/index.html | 359 ++++++++ files/zh-tw/learn/html/howto/index.html | 150 ++++ files/zh-tw/learn/html/index.html | 61 ++ .../advanced_text_formatting/index.html | 456 ++++++++++ .../creating_hyperlinks/index.html | 326 +++++++ .../document_and_website_structure/index.html | 283 ++++++ .../getting_started/index.html | 626 ++++++++++++++ .../html_text_fundamentals/index.html | 953 +++++++++++++++++++++ .../learn/html/introduction_to_html/index.html | 61 ++ .../the_head_metadata_in_html/index.html | 261 ++++++ .../index.html" | 502 +++++++++++ .../learn/html/multimedia_and_embedding/index.html | 53 ++ .../video_and_audio_content/index.html | 339 ++++++++ .../index.html | 104 +++ .../index.html" | 386 +++++++++ files/zh-tw/learn/html/tables/index.html | 34 + .../tables/\345\237\272\347\244\216/index.html" | 568 ++++++++++++ 18 files changed, 5837 insertions(+) create mode 100644 files/zh-tw/learn/html/forms/how_to_structure_an_html_form/index.html create mode 100644 files/zh-tw/learn/html/forms/index.html create mode 100644 files/zh-tw/learn/html/howto/index.html create mode 100644 files/zh-tw/learn/html/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/advanced_text_formatting/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/creating_hyperlinks/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/document_and_website_structure/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/getting_started/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/html_text_fundamentals/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/index.html create mode 100644 files/zh-tw/learn/html/introduction_to_html/the_head_metadata_in_html/index.html create 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/index.html create mode 100644 files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/index.html create mode 100644 files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/test_your_skills_colon__multimedia_and_embedding/index.html create 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/index.html create mode 100644 "files/zh-tw/learn/html/tables/\345\237\272\347\244\216/index.html" (limited to 'files/zh-tw/learn/html') 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 new file mode 100644 index 0000000000..b403666795 --- /dev/null +++ b/files/zh-tw/learn/html/forms/how_to_structure_an_html_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/html/forms/index.html b/files/zh-tw/learn/html/forms/index.html new file mode 100644 index 0000000000..589880794f --- /dev/null +++ b/files/zh-tw/learn/html/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/html/howto/index.html b/files/zh-tw/learn/html/howto/index.html new file mode 100644 index 0000000000..9a14c26039 --- /dev/null +++ b/files/zh-tw/learn/html/howto/index.html @@ -0,0 +1,150 @@ +--- +title: 使用HTML解決日常問題 +slug: Learn/HTML/Howto +translation_of: Learn/HTML/Howto +--- +
{{LearnSidebar}}
+ +

以下連結會給出 HTML 常見待解問題的方法

+ +
+
+

基本結構

+ +

HTML 文件的最基本結構應用。如果你是 HTML 新手,就先從這裡開始看。

+ + + +

基本文字語法

+ +

HTML 專攻於為文件提供語義資訊,因此 HTML 可以提供使用者更精準的文件資訊傳達方式。

+ + +
+ +
+

超連結

+ +

{{Glossary("hyperlink", "超連結")}}把 HTML 導覽變得相當容易,它可以這麼用:

+ + + +

圖片與多媒體

+ + + +

腳本與樣式

+ +

HTML 只建立文件的基礎架構,可以透過 {{glossary("CSS")}} 或腳本使內容呈現更具互動性。

+ + + +

嵌入內容

+ + +
+
+ +

不常見或進階的問題

+ +

除了上述的基本功能外,HTML 還提供許多進階功能讓使用者解決較複雜的問題。這些文章可以幫助你處理一些較不常見的情況:

+ +
+
+

表單

+ +

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

+ + + +

表格訊息

+ +

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

+ + + +

資料表示方式

+ + + +

互動性

+ + +
+ + +
+ +

     

diff --git a/files/zh-tw/learn/html/index.html b/files/zh-tw/learn/html/index.html new file mode 100644 index 0000000000..897bbcdd5e --- /dev/null +++ b/files/zh-tw/learn/html/index.html @@ -0,0 +1,61 @@ +--- +title: 學習 HTML :指南與教學 +slug: Learn/HTML +tags: + - Beginner + - Guide + - HTML + - Intro + - Learn + - NeedsTranslation + - Topic + - TopicStub + - 初心者 + - 指南 + - 超文本標記語言 +translation_of: Learn/HTML +--- +
{{LearnSidebar}}
+ +

為了建立網頁,你應該要先知道 {{Glossary('「HTML」')}} — 用來建造網站架構的科技。 HTML 是用來辨認網頁中的內容該如何被解讀,例如說被解讀為:一個段落(paragraph)、清單(list)、文件標題(heading)、連結(link)、圖片(images)、多媒體撥放器(multimedia player)、表單(form)或是任何一個可使用的「元素(elements)」,甚至是你自己定義的新元素。

+ +

學習途徑

+ +

理想上,你應該從學習 HTML 開始你的學習旅程。可以先從閱讀 HTML介紹(Introduction to HTML) 開始。接下來你可以開始閱讀以下的進階主題:

+ + + +

當你開始閱讀這主題時,你至少必須對使用電腦有基礎了解,以及會基本的上網 (諸如網頁瀏覽、了解網頁內容)。而你需要建立一個已安裝基本軟體 (詳細軟體請參閱Installing basic software)的基礎工作環境,並且了解如何建立與管理檔案(詳細請參閱Dealing with files) — 這些都包含在新手 Web 入門的章節裡。

+ +

建議你在開始學習 HTML 這個項目之前,可以先 從網際網路開始 瞭解是如何運作的。儘管知道網路的運作不是必要的;大部分的項目都在 HTML basics 的文章中 Introduction to HTML 這個章節更詳盡地介紹 模組 (module), albeit。

+ +

模組

+ +

這主題包含了以下幾個單元, 你可以根據以下順序來閱讀他們。強烈推薦從第一個單元開始讀起。

+ +
+
HTML介紹
+
這個單元為你提供一個平台,讓你熟悉重要的概念和語法、思考如何將HTML應用於文本、如何創建超鏈接以及使用HTML來構建網頁。
+
嵌入多媒體
+
本單元探索如何在你的網頁中使用HTML置入多媒體,包括置入圖像的各種方法,以及如何嵌入影片,聲音檔或甚至其他網頁。
+
表格
+
以一種易於理解、無障礙的方式在網頁上顯示表格數據可能是一個挑戰。此單元涵蓋基本的表格標記以及更複雜的功能,例如實行標題和摘要。
+
+ +

解決常見的 HTML 問題

+ +

利用HTML解決常見問題 提供部分連結,這些內容解釋了在創建網頁時如何使用HTML解決常見的問題:標題,添加圖像或視頻,強調內容,創建基本表單等等。

+ +

或許你還想看......

+ +
+
+
網站表單
+
這篇指南提供了一系列的文章,幫你掌握HTML表單的基本知識。對於與使用者互動,網站表單是一項十分有力的工具,最常使用於用戶數據蒐集,或控制使用者介面。但由於一些歷史與技術上的因素,並沒有顯著的方法發揮表單的潛力。在下面的指引中,我們將介紹網站表單所有基本面向,包括標記他們的HTML結構、設定控制器樣式、驗證數據及將數距提送至伺服器。
+
HTML
+
MDN的HTML參考文件的主要入口,包括詳細的元素和屬性參考-例如,如果您想知道元素具有哪些屬性或屬性具有什麼值,那麼這是一個很好的起點。
+
+
diff --git a/files/zh-tw/learn/html/introduction_to_html/advanced_text_formatting/index.html b/files/zh-tw/learn/html/introduction_to_html/advanced_text_formatting/index.html new file mode 100644 index 0000000000..3b5786613b --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/advanced_text_formatting/index.html @@ -0,0 +1,456 @@ +--- +title: Advanced text formatting +slug: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting +tags: + - HTML +translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
+ +

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less well-known, but still useful to know about (and this is still not a complete list by any means.) In here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
+ +

說明列表

+ +

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

+ +
soliloquy
+In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+monologue
+In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+aside
+In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
+ +

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description description) element. Let's finish marking up our example:

+ +
<dl>
+  <dt>soliloquy</dt>
+  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
+  <dt>monologue</dt>
+  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
+  <dt>aside</dt>
+  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.</dd>
+</dl>
+ +

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

+ +
+
soliloquy
+
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+
monologue
+
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of addtional background information.
+
+ +

Note that it is permitted to have a single term with multiple descriptions, for example:

+ +
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
+
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
+
+ +

Active learning: Marking up a set of definitions

+ +

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

+ +

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 the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 500) }}

+ +

Quotations

+ +

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

+ +

Blockquotes

+ +

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

+ +
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+ +

To turn this into a block quote, we would just do this:

+ +
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+ +

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

+ +
+

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

+
+ +

Inline quotations

+ +

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

+ +
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q></p>
+ +

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

+ +

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

+ +

Citations

+ +

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page, a better way to mark it up is put the {{htmlelement("cite")}} element next to the quote element. This is really meant to contain the name of the quote source — i.e. the name of the book, or name of the person that said the quote — but there is no reason why you couldn't link the text inside <cite> to the quote source in some way:

+ +
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+<cite>MDN blockquote page</cite></a>:
+</p>
+
+<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+
+<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
+<cite>MDN q page</cite></a>.</p>
+ +

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

+ +

Active learning: Who said that?

+ +

Time for another active learning example! In this example we'd like you to:

+ +
    +
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. +
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. +
  5. Include a <cite> element for each quote
  6. +
+ +

Search online to find appropriate quote sources.

+ +

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 the answer.

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 500) }}

+ +

Abbreviations

+ +

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

+ +
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
+
+<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
+ +

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

+ +

We use HTML to structure our web documents.

+ +

I think Rev. Green did it in the kitchen with the chainsaw.

+ +
+

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported as well in browsers as well as <abbr>, and has such as similar function that it was felt pointless to have both. Just use <abbr> instead.

+
+ +

Active learning: marking up an abbreviation

+ +

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 350) }}

+ +

Marking up contact details

+ +

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

+ +
<address>
+  <p>Chris Mills, Manchester, The Grim North, UK</p>
+</address>
+ +

One thing to remember however is that the <address> element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

+ +
<address>
+  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
+</address>
+ +

Superscript and subscript

+ +

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

+ +
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
+<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
+<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
+ +

The output of this code looks like so:

+ +

My birthday is on the 25th of May 2001.

+ +

Caffeine's chemical formula is C8H10N4O2.

+ +

If x2 is 9, x must equal 3 or -3.

+ +

Representing computer code

+ +

There are a number of elements available for marking up computer code:

+ + + +

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

+ +
<pre><code>var para = document.querySelector('p');
+
+para.onclick = function() {
+  alert('Owww, stop poking me!');
+}</code></pre>
+
+<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
+
+<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
+
+
+<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
+
+<pre>$ <kbd>ping mozilla.org</kbd>
+<samp>PING mozilla.org (63.245.215.20): 56 data bytes
+64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
+ +

The above code will look like so:

+ +

{{ EmbedLiveSample('Representing_computer_code','100%',300) }}

+ +

Marking up times and dates

+ +

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

+ +
<time datetime="2016-01-20">20 January 2016</time>
+ +

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

+ + + +

But these different forms cannot be easily recognised by the computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach a unambiguous, machine-readable time/date for this purpose.

+ +

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

+ +
<!-- Standard simple date -->
+<time datetime="2016-01-20">20 January 2016</time>
+<!-- Just year and month -->
+<time datetime="2016-01">January 2016</time>
+<!-- Just month and day -->
+<time datetime="01-20">20 January</time>
+<!-- Just time, hours and minutes -->
+<time datetime="19:30">19:30</time>
+<!-- You can do seconds and milliseconds too! -->
+<time datetime="19:30:01.856">19:30:01.856</time>
+<!-- Date and time -->
+<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
+<!-- Date and time with timezone offset-->
+<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
+<!-- Calling out a specific week number-->
+<time datetime="2016-W04">The fourth week of 2016</time>
+ +

Summary

+ +

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

diff --git a/files/zh-tw/learn/html/introduction_to_html/creating_hyperlinks/index.html b/files/zh-tw/learn/html/introduction_to_html/creating_hyperlinks/index.html new file mode 100644 index 0000000000..059cfa427c --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/creating_hyperlinks/index.html @@ -0,0 +1,326 @@ +--- +title: Creating hyperlinks +slug: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
+ +

超連結(Hyperlinks)真的超級重要 — 它造就了我們現今所熟知的網路。這篇文章將會介紹超連結的使用語法,並且探討建立它們的最佳實踐方法。

+ + + + + + + + + + + + +
需求:我們在 HTML 入門 中介紹過的 HTML 基礎,以及在 HTML 的文字基礎知識 中介紹過的文字格式化技巧。
目標:學習如何有效地使用超連結,並利用它們來連結多個檔案。
+ +

什麼是超連結?

+ +

超連結可說是網路中最令人振奮的革新技術。當然啦,早在網路技術萌芽之初,它們就已經在那了,它們正是網路之所以被稱為「網路」的最大原因 — 它讓我們的文件能任意地與其他文件(或者資源)相互連結(或是連結文件中的特定部份),讓我們能透過一個簡單的網路位址來經營我們的網路應用(相較之下,本機應用(native apps)就必須要安裝在主機上才能使用)。幾乎所有的網路內容都能被轉換成一個連結,讓網路瀏覽器在這些連結被點擊或觸發之後,跳轉到該網路位址({{glossary("URL")}})上。

+ +
+

Note: URL 能夠指向 HTML 檔案、純文字檔案、圖片、文字文件、影音檔案等等可存在網路上的東西。如果網路瀏覽器不知道如何顯示或者處理該檔案的話,它會問你想要開啟這個檔案(將檔案交由本機應用來處理)還是要下載該檔案(意即你可以待會兒再處理)。

+
+ +

以 BBC 的主頁為例,裡面就包含了非常多的連結,各自連到不同新聞、網站的其它地方(導覽功能),或者登入/註冊頁面等等。

+ +

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

+ +

解析連結

+ +

一個基本的連結由 {{htmlelement("a")}} 元素包裹一段文字而成(當然也不一定要是文字,見下方的{{anch("區塊級連結")}}),同時,你需要將網路位址填入 {{htmlattrxref("href", "a")}} 屬性中,這個屬性有時也被叫做超文字參考(Hypertext Reference)目標(target)

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
+</p>
+ +

這會產生以下結果:

+ +

I'm creating a link to the Mozilla homepage.

+ +

利用 title 屬性來添加額外資訊

+ +

另外一個你可能會想在連結中附加的屬性是 title,它的目的是攜帶一個補充訊息到連結上,好比說目標網頁有什麼樣的資訊,或者是一些警告訊息,範例如下:

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/"
+   title="The best place to find more information about Mozilla's
+          mission and how to contribute">the Mozilla homepage</a>.
+</p>
+ +

這將會產生以下結果(當游標移到連結上方時,標題會以提示的形式出現):

+ +

I'm creating a link to the Mozilla homepage.

+ +
+

Note: 連結標題只有在游標停在連結上方時才會出現,也就是說那些只依賴鍵盤來瀏覽網頁的人將會很難看到這個訊息,因此,如果說標題資訊對網頁易用性(usability)有著重大影響的話,你應該把它放在大家都看得到的地方,比方說放在一般的文字元素裡。

+
+ +

不要只用看的:建立你自己的範例連結

+ +

主動學習時間!我們想要你用自己的文字編輯器來撰寫一個 HTML 文件(你可以修改我們的入門範本,那應該就很夠用了)。

+ + + + + +

就像先前所提到的,你可以將任何內容轉換成連結,就算是區塊級元素也沒問題!如果你有一張圖片要轉換成連結,你可以把圖片元素放在 <a> 標籤裡,像這樣:

+ +
<a href="https://www.mozilla.org/en-US/">
+  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
+</a>
+ +
+

Note: 在往後的教學中,你還會學到更多的圖片使用技法。

+
+ +

快速理解 URL 和路徑

+ +

在完全搞懂連結標的(link target)之前,你必須要先瞭解什麼是 URL 和檔案路徑,而這個小節就是要帶你來看這些東西。

+ +

URL 全名為 Uniform Resource Locator (一致資源定位器,俗稱網址),是一條用來指出某樣東西在網路上的位址的字串。比如說 Mozilla 的英文主頁就是位在 https://www.mozilla.org/en-US/

+ +

URL 利用路徑來找到檔案,而路徑會指出你所感興趣的檔案位於檔案系統上的什麼地方。現在讓我們來看個簡單的目錄結構範例(請見我們的建立超連結目錄)。

+ +

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

+ +

creating-hyperlinks 是這個目錄結構的根目錄(root),當你在本地端撰寫網站時,你會將整個網站都放在這樣的資料夾中。在我們的根目錄裡有 index.htmlcontacts.html 兩個檔案,在現實的情況中,index.html 會是我們的首頁或者登陸頁面(landing page,網站或它的某部份的進入點)。

+ +

我們的根目錄中有兩個子目錄 — pdfsprojects,它們各自都有一個檔案在裡頭,分別是 project-brief.pdfindex.html。請記得,你可以很愉快地在一個專案中擁有兩個 index.html,只要它們處在檔案系統上的不同位址。很多網站都會這麼做,第二個 index.html 可能會拿來當作是與專案有關資訊的主登陸頁面。

+ + + +
+

Note: 你可以將多個這種語法組成一個較為複雜的 URL,例如:../../../complex/path/to/my/file.html

+
+ +

文件片段 (Document fragments)

+ +

並不是每次都只能連到文件的頂端,你也可以連到 HTML 文件中的某個部分,而這個部分叫做文件片段(document fragment)。要做到這件事,你得先為你要連的元素設定 {{htmlattrxref("id")}} 屬性,通常你可以把連結設在標題(heading)上,像是下面這樣:

+ +
<h2 id="Mailing_address">Mailing address</h2>
+ +

要連到特定的 id,你得在你的 URL 的後面加上一個 # 號,像這樣:

+ +
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
+ +

你甚至可以利用文件片段來連到同個文件的其他部分

+ +
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
+ +

絕對 URL vs. 相對 URL

+ +

你會在網路上看到兩個名詞,絕對 URL(absolute URL)相對 URL(relative URL):

+ +

絕對 URL:指向網路上的絕對位址,裡頭包含協定({{glossary("protocol")}})和網域名稱({{glossary("domain name")}})。舉個例子,假設一個 web server 的根目錄有一個 projects 目錄,裡面放著一個 index.html,該網站的網域為 http://www.example.com,則網頁可以透過網址 http://www.example.com/projects/index.html 來取得 (或寫成 http://www.example.com/projects/ 也行,因為大多的 web server 都能在 URL 沒有明確指出時,自動找尋如 index.html 之類的登陸頁面)。

+ +

絕對 URL 無論在什麼地方使用,它都會代表同一個位址。

+ +

相對 URL:指向一個檔案的相對位址,這跟我們在先前看到的非常類似。舉例來說,如果我們想要從 http://www.example.com/projects/index.html 連到同一目錄下的 PDF 檔,URL 就只要檔名就好 — 像是 project-brief.pdf — 不需要其它的資訊。如果那個 PDF 放在 projects 中叫做 pdfs 的子目錄裡,其相對連結就是 pdfs/project-brief.pdf (等效的絕對 URL 為 http://www.example.com/projects/pdfs/project-brief.pdf)。

+ +

相對 URL 指向的位址會受到檔案所在的真正位址影響 — 舉例來說,如果我們將 index.html 移出 projects,並放在網站的根目錄中 (也就是在最上層中),裡頭指向 pdfs/project-brief.pdf 的相對 URL 連結會指到 http://www.example.com/pdfs/project-brief.pdf,而非 http://www.example.com/projects/pdfs/project-brief.pdf

+ +

當然,project-brief.pdfpdfs 的位置不會因為你移動 index.html 就改變 — 這會使得你的連結指到錯誤的地方,你一定得非常小心!

+ +

連結的最佳實踐

+ +

撰寫連結時有幾個最佳實踐方法,現在讓我們來看看吧。

+ + + +

使用明確的字詞

+ +

要在你的網頁上加入連結非常簡單,但這還不夠,我們必須確保連結能夠被所有讀者取用到,無論他們的背景或者使用的工具為何。比如說:

+ + + +

我們來看幾個例子:

+ +

好的連結文字:下載 Firefox

+ +
<p><a href="https://firefox.com/">
+  下載 Firefox
+</a></p>
+ +

不好的連結文字:點這裡來下載 Firefox

+ +
<p><a href="https://firefox.com/">
+  點這裡
+</a>
+來下載 Firefox</p>
+
+ +

其它小訣竅:

+ + + +

盡可能使用相對連結

+ +

經過之前的說明,你可能會覺得無論如何都應該採用絕對連結,畢竟它們不會像相對連結一樣,因為頁面被搬移而失效。然而,對於相同網站內的連結,你應該盡量使用相對連結 (連到別的網站的連結必須使用絕對連結),原因如下:

+ + + +

要連到非 HTML 的資源時請先聲明

+ +

當連結連至一個需要下載的資源 (像是 PDF 或 Word 文件) 或是串流 (如影音串流) 或是其他有潛在未知影響的東西 (開啟彈出式視窗或者載入 Flash movie) 時,你應該要加上一些文字來預示,以下就是幾個非常惱人的情境:

+ + + +

讓我們來看一些可以改善這些情況的方法:

+ +
<p><a href="http://www.example.com/large-report.pdf">
+  下載銷售報告(PDF, 10MB)
+</a></p>
+
+<p><a href="http://www.example.com/video-stream/" target="_blank">
+  觀看影片(將在新分頁開啟串流,HD 畫質)
+</a></p>
+
+<p><a href="http://www.example.com/car-game">
+  遊玩賽車遊戲(需要 Flash)
+</a></p>
+ +

當連結會觸發下載時,使用下載屬性

+ +

當你連結一個需要下載的資源時,你可以使用 download 屬性來提供一個預設的儲存檔名。以下範例是最新版的 Windows 版 Firefox 的下載連結:

+ +
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
+   download="firefox-latest-64bit-installer.exe">
+  下載Windows上的最新版Firefox (64-bit) (English, US)
+</a>
+ +

不要只用看的:建立一個導覽選單

+ +

在這次練習中,我們想要你利用導覽列來將許多網頁連結在一起,創造出一個具有多個頁面的網站。這是一個很常見的網站建造方式 — 每一個網頁都使用同樣的網頁結構,其中包含相同的導覽選單,這樣子一來,當連結被點擊時,會讓人以為還留在原地,但內容卻倏忽更迭。

+ +

你需要先在一個目錄中建立下面這四個網頁的複本 (你可以在 navigation-menu-start 目錄下找到完整的清單):

+ + + +

接著,你可以這麼做:

+ +
    +
  1. 在指定的地方添加一個無序列表,裡面放著可以連到的網頁名稱。因為導覽選單其實就是一個連結的列表,所以這麼做在語義上沒什麼問題。
  2. +
  3. 把每一個網頁名稱變成超連結。
  4. +
  5. 把導覽選單複製到每一個頁面上。
  6. +
  7. 把每個網頁中,連到自己的連結移除,因為這種連結毫無意義且令人困惑,此外,無連結的文字可以用來提示使用者的所在位置。
  8. +
+ +

完成後的範例應該會長這樣:

+ +

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

+ +
+

Note: 如果你卡住了,或者不確定有沒有做對,你可以到 navigation-menu-marked-up 目錄來偷瞄答案。

+
+ +

E-mail 連結

+ +

你可以建立一個連結或按鈕,使得它被點擊之後,開啟一個正在撰寫中的電子郵件訊息。這可以透過 {{HTMLElement("a")}} 元素和 mailto: URL scheme 來達成。

+ +

多數情況 mailto: 會填入收信人的電子郵件地址。例如:

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+
+ +

它的結果會像是這樣:Send email to nowhere

+ +

事實上,電子郵件地址是選填的。如果你將它留空 (也就是說,你的 {{htmlattrxref("href", "a")}} 只寫了 "mailto:"),使用者的 mail client 會開啟一個寄信視窗,其中並沒有指定收信人,這在使用「分享」連結時非常有用,使用者可以自行決定要寄給誰。

+ +

指定細節

+ +

除了電子郵件地址之外,你還可以提供其他資訊,事實上,任何標準的郵件標頭欄位都能被加到  mailto URL 中,常見的有主旨(subject)、副本(cc)以及主體(body) (這個雖然不是真的標頭欄位,但能讓你放一條簡短的訊息在新郵件的主體中)。每個欄位與它的值被定義成一組查詢項(query term)。

+ +

下面是一個包含 cc、bcc(密件副本)、subject 和 body 的範例:

+ +
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
+  Send mail with cc, bcc, subject and body
+</a>
+ +
+

Note: 每一個欄位的值必須以 URL 編碼,也就是將空白及不可印字元(不可見的字元如縮排(tabs)、回車(carriage return)、換頁(page breaks)等等)轉換成百分號編碼。也請注意這裡使用問號(?)來分隔主要 URL 和其他欄位;以 & 來分隔 mailto: URL 中的不同的欄位,這是標準的 URL 查詢記號(query notation)。你可以閱讀 GET 方法來得知有那些常用的查詢記號。

+
+ +

以下是 mailto URL 的其他例子:

+ + + +

小試身手!

+ +

你已經讀完這個章節囉,但你有掌握箇中的重點嗎?你可以在繼續閱讀後面的章節之前,先進行一些測驗 — 請前往小試身手:超連結。

+ +

總結

+ +

總而言之,以上就是超連結的介紹了! 稍後你在後續的課程中學到如何位連結增添樣式時,還會再碰到它們。HTML 的下一章,我們將繼續討論文字語義(text semantics),並看一些進階/不常見的特性,相信你會獲益良多的 — 下一站是:進階文字格式化技巧!

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

+ +

在本主題中的內容

+ + diff --git a/files/zh-tw/learn/html/introduction_to_html/document_and_website_structure/index.html b/files/zh-tw/learn/html/introduction_to_html/document_and_website_structure/index.html new file mode 100644 index 0000000000..2a4a379123 --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/document_and_website_structure/index.html @@ -0,0 +1,283 @@ +--- +title: Document and website structure +slug: Learn/HTML/Introduction_to_HTML/Document_and_website_structure +translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

{{glossary("HTML")}} 不僅能夠定義網頁的單獨部分(例如“段落”或“圖片”),還可以使用區塊級元素(例如“標題欄”、“導覽選單”、“主內容列”)來定義網站中的複合區域。本文將探討如何規劃基本的網站結構,並根據規劃的結構來編寫 HTML。

+ + + + + + + + + + + + +
預備知識:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
學習目標:學習使用語義標籤來建立文本,建置簡單的網站結構。
+ +

文本的基本組成

+ +

網頁有各式各樣的外觀,但是除了全螢幕影片、遊戲或藝術作品頁面外,都傾向於使用類似的標準元件:

+ +
+
頁首:
+
通常橫跨於整個頁面頂部有一個大標題。這是網站的主要資訊,通常存在於所有網頁。
+
導覽列:
+
指向網站各個主要區段的超連結。通常用選單按鈕、連結或頁簽來表示。類似於頁首,導航列通常應在所有網頁之間保持一致,否則會讓用戶感到疑惑,甚至無所適從。許多web 設計人員認為導航列是頁首的一部分,而不是獨立的元件,但這並非絕對;還有人認為,兩者獨立可以提供更好的無障礙訪問特性,因為螢幕可以更清晰地分辨二者。
+
主要內容:
+
中心的大部分區域是當前網頁大多數的獨有內容,例如影片、文章、地圖、新聞等。這些內容是網站的一部分,且會因頁面而異。
+
側邊攔:
+
一些外圍資訊、連結、引用、廣告等。通常與主內容相關(例如一個新聞頁面上,側邊欄可能包含作者資訊或相關文章連結)。
+
頁尾:
+
橫跨頁面底部的狹長區域。和頁首一樣,頁尾是放置共用資訊(比如版權聲明或聯繫方式)的,一般使用較小字體,且通常為次要內容。還可以通過提供快速訪問連結來進行{{Glossary("SEO")}} 。
+
+ +

一個“典型的網站”可能會這樣佈局:

+ +

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

+ +

用於構造內容的HTML

+ +

上面顯示的簡單範例並不美觀,但對於說明典型的網站佈局範例來說是非常好的。 有些網站上有更多欄,有些則複雜得多,但是您知道了。 使用正確的CSS,您幾乎可以使用任何元素來包裹不同的部分,並使其看起來像您想要的樣子,但是如前所述,我們需要遵守語義並將正確的元素用於正確的運行。

+ +

這是因為視覺效果並不能說明整個故事。 We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

+ +
+

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

+
+ +

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

+ +

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

+ + + +

Active learning: exploring the code for our example

+ +

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+
+    <title>My page title</title>
+    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
+    <link rel="stylesheet" href="style.css">
+
+    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
+    <!--[if lt IE 9]>
+      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
+    <![endif]-->
+  </head>
+
+  <body>
+    <!-- Here is our main header that is used across all the pages of our website -->
+
+    <header>
+      <h1>Header</h1>
+    </header>
+
+    <nav>
+      <ul>
+        <li><a href="#">Home</a></li>
+        <li><a href="#">Our team</a></li>
+        <li><a href="#">Projects</a></li>
+        <li><a href="#">Contact</a></li>
+      </ul>
+
+       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
+
+       <form>
+         <input type="search" name="q" placeholder="Search query">
+         <input type="submit" value="Go!">
+       </form>
+     </nav>
+
+    <!-- Here is our page's main content -->
+    <main>
+
+      <!-- It contains an article -->
+      <article>
+        <h2>Article heading</h2>
+
+        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
+
+        <h3>Subsection</h3>
+
+        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
+
+        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
+
+        <h3>Another subsection</h3>
+
+        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
+
+        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
+      </article>
+
+      <!-- the aside content can also be nested within the main content -->
+      <aside>
+        <h2>Related</h2>
+
+        <ul>
+          <li><a href="#">Oh I do like to be beside the seaside</a></li>
+          <li><a href="#">Oh I do like to be beside the sea</a></li>
+          <li><a href="#">Although in the North of England</a></li>
+          <li><a href="#">It never stops raining</a></li>
+          <li><a href="#">Oh well...</a></li>
+        </ul>
+      </aside>
+
+    </main>
+
+    <!-- And here is our main footer that is used across all the pages of our website -->
+
+    <footer>
+      <p>©Copyright 2050 by nobody. All rights reversed.</p>
+    </footer>
+
+  </body>
+</html>
+ +

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

+ +

HTML layout elements in more detail

+ +

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

+ + + +

Non-semantic wrappers

+ +

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

+ +

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

+ +
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
+him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
+play, the lights should be down low]</span>.</p>
+ +

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

+ +

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

+ +
<div class="shopping-cart">
+  <h2>Shopping cart</h2>
+  <ul>
+    <li>
+      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
+      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
+    </li>
+    <li>
+      ...
+    </li>
+  </ul>
+  <p>Total cost: $237.89</p>
+</div>
+ +

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

+ +
+

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

+
+ +

Line breaks and horizontal rules

+ +

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

+ +

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

+ +
+
<p>There once was a man named O'Dell<br>
+Who loved to write HTML<br>
+But his structure was bad, his semantics were sad<br>
+and his markup didn't read very well.</p>
+
+ +

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with <br> elements in the code, the markup renders like this:

+ +

{{EmbedLiveSample('line-break-live-sample', '100%', '125px', '', '', 'hide-codepen-jsfiddle')}}

+ +

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

+ +
+
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
+<hr>
+<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
+
+ +

Would render like this:

+ +

{{EmbedLiveSample('horizantal-rule-live-sample', '100%', '185px', '', '', 'hide-codepen-jsfiddle')}}

+ +

Planning a simple website

+ +

Once you've planned out the structure of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages, this can be fairly simple, and fun!

+ +
    +
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. +
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. +
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. +
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. +
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. +
+ +

Active learning: create your own sitemap

+ +

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

+ +
+

Note: Save your work somewhere; you might need it later on.

+
+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find a detailed assessment that tests these skills at the end of the module; see Structuring a page of content. We'd advise going through the next article in the series first and not just skipping to it though!

+ +

Summary

+ +

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/html/introduction_to_html/getting_started/index.html b/files/zh-tw/learn/html/introduction_to_html/getting_started/index.html new file mode 100644 index 0000000000..b68ccd2b73 --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/getting_started/index.html @@ -0,0 +1,626 @@ +--- +title: Getting started with HTML +slug: Learn/HTML/Introduction_to_HTML/Getting_started +translation_of: Learn/HTML/Introduction_to_HTML/Getting_started +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

本文將探討 HTML 最基本的部分。首先,我們將會定義元素(elements)、屬性(attributes)以及其它你可能聽過的重要名詞,然後講解該如何使用它們。我們也會告訴你典型的 HTML 頁面以及其中的元素是如何構成的,以及解釋其他重要的基礎語言特性。在此過程中,我們會撰寫一些 HTML 來引發你的興趣!

+ + + + + + + + + + + + +
需求:基礎電腦能力、已安裝需要的基本軟體、並知道如何操作檔案
目標:對 HTML 產生初步認識、並練習如何撰寫 HTML 元素。
+ +

什麼是 HTML?

+ +

{{glossary("HTML")}} (Hypertext Markup Language) 並不是一種程式語言,而是用來告訴瀏覽器該如何呈現網頁的標記式語言(markup language)。它可以很複雜也可以很陽春,端看網頁開發者如何構思。HTML 由一系列的元素({{glossary("Element", "elements")}})組成,你將利用它們來圍住、包裹,或者說標記(mark up)網頁中的每個部分,使它們在外表或行為上呈現某種特定風貌。被標籤({{glossary("Tag", "tags")}})包住的內容會變成超連結,或者斜體字,以及諸如此類的功能,舉例來說,請看下列內容:  

+ +
My cat is very grumpy
+ +

如果我們想要讓這行字獨立出來,不讓它跟其他東西排在一起,我們可以用段落標籤( paragraph tag {{htmlelement("p")}})讓它自成段落:

+ +
<p>My cat is very grumpy</p>
+
+ +
+

注意:
+ HTML 中的元素是不區分大小寫的
+ 例如 : 一個 {{htmlelement("title")}} 標籤可以寫成<title><TITLE><Title><TiTlE>,之類的形式,都沒有問題
+ 通常來說,為了保持一致性(consistency)、可讀性(readability),以及其他可能的原因,最好還是以小寫來撰寫標籤

+
+ +

分析 HTML 元素

+ +

讓我們更深入地探索段落中的元素:

+ +

+ +

元素中主要的內容有: 

+ +
    +
  1. 起始標籤(opening tag):它包含了元素的名字(在這裡是 p),夾在一對 <、> (angle brackets)之間。它指明元素從何開始生效 — 在上例中則代表段落的開始。
  2. +
  3. 結束標籤(closing tag):結束標籤和起始標籤長得差不多,只不過它在名字前面還多加了一條斜線 (forward slash) 。它表示元素結束的地方 — 在上例中表示該段落的結束。忘記加上結束標籤是初學者常犯的錯誤,這將導致奇怪的結果。
  4. +
  5. 內容(content): 元素的內容。在上例中就是一段文字。
  6. +
  7. 元素(element): 以上三者加起來就是元素。
  8. +
+ +

不要光是看: 創造你的第一個 HTML 元素

+ +

編輯下面輸入區域中的文字,嘗試用 <em> 和 </em> 標籤包裹住文字(把 <em> 放在文字前面來起始元素,把 </em> 放在後面來結束元素) ,這會使得文字變成斜體字。你可以在下面的輸出區域看到更新後的變化。

+ +

如果你不小心打錯了,你可以按下 Reset 鍵來重置。如果你卡關了,你可以點擊 Show solution 鍵來偷看答案。

+ + + +

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

+ +

巢狀元素(Nesting elements)

+ +

你可以把元素放進另一個元素裡面 — 這叫做巢套(nesting)。比如說,我們想要強調我們的貓咪非常兇,我們可以用{{htmlelement("strong")}}元素來包住 "very" 這個字,這樣就可以標註我們想要強調的字:

+ +
<p>My cat is <strong>very</strong> grumpy.</p>
+ +

你必須確保你的元素正確地巢套:在上述範例中,我們先用了 p 元素,然後才用 strong 元素,因此我們必須先關閉 strong 元素,再關閉 p 元素。下面是錯誤示範:

+ +
<p>My cat is <strong>very grumpy.</p></strong>
+ +

這些元素必須要正確地開啟與關閉,它們與其他元素的內外關係要相當明確。如果它們像上例這樣交互重疊,你的網頁瀏覽器將無法解讀,只能盡可能地猜測你的意思,因此你很有可能會得到一個不如預期的結果。所以,別這樣做!!

+ +

區塊級元素 vs. 行內元素(Block versus inline elements)

+ +

在 HTML 中有兩種你應該要知道的重要元素類別 — 區塊級元素(block-level elements)和行內元素(inline elements)。

+ + + +

以下面這個例子來說:

+ +
<em>first</em><em>second</em><em>third</em>
+
+<p>fourth</p><p>fifth</p><p>sixth</p>
+
+ +

{{htmlelement("em")}} 是一個行內元素,所以你可以看到下面的例子中,前三個元素互相緊鄰在同一行,兩兩中間並無任何空白。另一方面,{{htmlelement("p")}} 是一個區塊級元素,所以每個元素都自成一行,並且上下都有一些空間。(這些空間是由於瀏覽器套用預設的CSS styling到這些段落上的緣故)。

+ +

{{ EmbedLiveSample('區塊級元素_vs._行內元素Block_versus_inline_elements', 700, 200, "", "") }}

+ +
+

Note: HTML5 重新定義了元素類別:請見 Element content categories。新的定義比先前所定義的更為準確且少歧義性,因此它們也同時比 block 和 inline 還來得複雜,所以我們選擇在這裡繼續使用這個觀念。

+
+ +
+

Note: 在本主題所使用的 block 與 inline 這兩個名詞,不應與 CSS 的 boxes 種類混淆。它們在預設時是很像的,但改變 CSS 的顯示型態(display type)並不會改變元素的類別,也不會影響該元素能包含或被包含的元素類別。HTML5 之所以會重新定義元素類別,部分也是基於此一原因。

+
+ +
+

Note: 你可以查看 block element 與 inline element 分別有哪些元素 — 請見 Block-level elementsInline elements

+
+ +

空元素(Empty elements)

+ +

不是所有元素都符合起始標籤、內容、結束標籤的格式。有些元素只有一個標籤,這些標籤通常用來在文件中插入/嵌入物件。例如 {{htmlelement("img")}} 元素便是用來在當前位置嵌入圖片檔:

+ +
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
+ +

這將會產生下面的結果:

+ +

{{ EmbedLiveSample('空元素Empty_elements', 700, 300, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: 空元素有時也被稱作 void elements。

+
+ +

屬性(Attributes)

+ +

你也可以在元素中加入屬性,像是:

+ +

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

+ +

屬性有著關於元素的額外資訊,但你並不會想要顯示它們。在這個例子中 class 屬性讓你能夠賦予一個元素辨別名稱,稍後就能用這個名稱來指定元素的樣式及其他的東西。

+ +

一個屬性應該要有:

+ +
    +
  1. 一個空白,用來隔開屬性和元素名稱(或者前一個屬性,如果該元素已經有一個以上的屬性的話)。
  2. +
  3. 屬性名稱以及一個接在其後的等號。
  4. +
  5. 屬性值以及一對包著它的引號。
  6. +
+ +

主動學習: 在元素中加入屬性

+ +

我們再舉另外一個元素的例子 {{htmlelement("a")}} 代表 anchor (錨),而這個元素會讓被它包裹住的內容變成一個超連結。它可以和很多種屬性搭配,以下僅列出幾種:

+ + + +

請編輯下面輸入區的文字,使它變成一個通往你最喜歡的網站的連結。

+ +
    +
  1. 首先,加入<a> 元素。
  2. +
  3. 再來,加入 href 屬性以及 title 屬性。
  4. +
  5. 最後,將 target 屬性設定為在新分頁中開啟。
  6. +
+ +

你將會在底下的輸出區域裡面即時地看到你改動產生的變化。當你完成後,你應該會看到一個連結;當你滑過時,連結將顯示 title 屬性的內容;當你點擊連結時,將會導向到 href 元素中的網址。切記,你需要以空白隔開元素名字以及每一個屬性。 

+ +

如果你不小心打錯了,你可以按下 Reset 鍵重置。如果你卡關了,可以點擊 Show solution 鍵來偷看答案。

+ + + +

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

+ +

布林屬性(Boolean attributes)

+ +

你有時會看到一些沒有值的屬性,這完全是可行的。它們叫做布林屬性,他們只能附帶一個值,而這個值一般來說會和屬性的名字一樣。以 {{htmlattrxref("disabled", "input")}} 屬性來說,你可以把它指派為 input 元素的屬性,使得輸入文字的框框變得不能輸入文字。

+ +
<input type="text" disabled="disabled">
+ +

你可以把它寫得更簡短(在下面的例子中,我們也寫出了沒有 disabled 屬性的 input 元素供你參考,讓你更了解兩者的差別):

+ +
<input type="text" disabled>
+
+<input type="text">
+
+ +

結果 :

+ +

{{ EmbedLiveSample('布林屬性Boolean_attributes' , 700, 100, "", "", "hide-codepen-jsfiddle") }}

+ +

忘記加屬性值的引號

+ +

當你看遍全世界的網頁,你就會發現各種千奇百怪的標記風格(markup style),包括沒加引號的屬性值。這在某些情況是被允許的,但在其他情況下則會使屬性結果不如預期。沿用我們之前的例子,我們先只用 href 屬性,如下:

+ +
<a href=https://www.mozilla.org/>favourite website</a>
+ +

看起來沒甚麼問題,但是,一旦我們加上 title 屬性時,就會造成錯誤的結果: 

+ +
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
+ +

此時瀏覽器會誤解你的標記,認為 title 屬性其實是三個屬性:一個值為 "The" 的標題屬性,以及兩個布林屬性 Mozilla 和 homepage。這絕對不是你想要的結果,而且會導致錯誤或者意想不到的行為。你可以看看下面的示範,把你的游標移到連結上,看看會出現什麼提示!

+ +

{{ EmbedLiveSample('忘記加屬性值的引號', 700, 100) }}

+ +

我們建議不管怎樣都要加屬性引號,避免這些錯誤,同時增加原始碼的可讀性。

+ +

要用單引號還是雙引號? (Single or double quotes?)

+ +

在這個章節中,你會發現所有的屬性都是使用雙引號,而你可能會發現其他人的 HTML 中使用的是單引號。這純粹是個人風格,你可以依照你個人的喜好去使用它們。下面兩行的意思是相同的:

+ +
<a href="http://www.example.com">A link to my example.</a>
+
+<a href='http://www.example.com'>A link to my example.</a>
+ +

但是,你應該確認你沒有混著使用它們。下面這行則會造成錯誤!

+ +
<a href="http://www.example.com'>A link to my example.</a>
+ +

如果你在你的 HTML 中使用其中一種引號,你就可以包裹另外一種引號:

+ +
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
+ +

不過,如果你想要包裹相同種類的引號,你就必須要用到 HTML entities。例如,以下範例是錯的:

+ +
 <a href='http://www.example.com' title='Isn't this fun?'>A link to my example.</a> 
+ +

你應該要這樣寫:

+ +
<a href='http://www.example.com' title='Isn&#39;t this fun?'>A link to my example.</a> 
+ +

解析 HTML 文檔

+ +

以上講述了 HTML 中個別元素的基礎知識,但是單獨使用它們,並沒有多大用處。所以現在就讓我們來看看如何將這些元素組成一個 HTML 網頁吧:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

這裡有:

+ +
    +
  1. <!DOCTYPE html>: 文件類型(doctype)。 在很久很久以前,當 HTML 還年輕的時候(約莫在西元 1991 年左右),文件類型是要作為一系列規範的連結,HTML 網頁必須要遵守這些規範才會被當作是好的 HTML,比如說具備自動錯誤檢查和其他有用的東西等。在那個時候,它們看起來像這樣: + +
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    + 不過,現在已經沒有人在乎它們了,它們只是個歷史痕跡,需要形式上地被引入,以確保一切正常。<!DOCTYPE html> 是字數最短的有效 doctype。你只需要知道這些就夠了。
  2. +
  3. <html></html>: {{htmlelement("html")}} 元素。該元素包裹住頁面的所有內容,有時也被稱作根元素(root element)。
  4. +
  5. <head></head>: {{htmlelement("head")}} 元素。這個元素放著你想含括的所有重要資訊,這些資訊不會呈現在網頁瀏覽者眼前。這些東西包括,顯示於搜尋結果的關鍵字、頁面說明、CSS 等等。你將會在這個系列的下個章節中學到更多有關這部分的知識。
  6. +
  7. <meta charset="utf-8">: 這個元素指定你的文件使用 UTF-8 為字元編碼,這種編碼含有這世上大部分語言的字元,理論上可以處理所有你想放文字內容,因此建議大家都要使用這種編碼,它能幫你免去許多煩惱。
  8. +
  9. <title></title>: {{htmlelement("title")}} 元素。這是用來設定網頁名稱的,它會顯示在分頁標籤上,當你將該網頁加入書籤或加入最愛時,則是用來形容這個網站。
  10. +
  11. <body></body>: {{htmlelement("body")}} 元素含括了所有你想要給網頁瀏覽者看到的內容,不管是文字、圖片、遊戲、可以播放的音樂或其他東西。
  12. +
+ +

主動學習: 在HTML文檔中加入一些特徵

+ +

如果你想試試看在你的電腦上寫一些 HTML,你可以: 

+ +
    +
  1. 複製上面的 HTML 範例。
  2. +
  3. 在你的文字編輯器中建立一個新檔案。
  4. +
  5. 將剛複製的 HTML 範例貼到新開的檔案裡。
  6. +
  7. 將檔案儲存為 index.html
  8. +
+ +
+

Note: 你也可以在這找到基本的 HTML 範本: MDN Learning Area Github repo

+
+ +

接著你就可以用網頁瀏覽器開啟你的檔案,看看這些原始碼會被渲染(rendered)成什麼樣子,然後編輯原始碼並重新整理瀏覽器,再看看會變成怎樣。目前你的網頁會長這樣:

+ +

A simple HTML page that says This is my page在這個練習中,你可以在自己的電腦中撰寫原始碼,就像上面寫的一樣,或者你可以在底下的範例視窗中進行編輯(該視窗僅表示 {{htmlelement("body")}} 元素的內容) 我們希望你依照以下的步驟逐步前行:

+ + + +

如果你不小心打錯了,你可以用 Reset 鍵重置。如果你卡關了,可以點擊 Show solution 鍵來偷看答案。

+ + + +

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

+ +

HTML中的空格(Whitespace)

+ +

在上面的範例中,你可能會發現原始碼中有許多空格,其實這是完全不需要的,下面兩段原始碼會有相同的結果: 

+ +
<p>Dogs are silly.</p>
+
+<p>Dogs        are
+         silly.</p>
+ +

不管你用多少空格(whitespace,包括空白字元與換行字元),HTML 的語法分析器都只會留下一個空格。所以說,為什麼要用這麼多空格呢?答案是為了增加可讀性 — 適當的排版會讓人更明白你的原始碼,所以千萬不要把你的原始碼擠成一團,讓它們變得雜亂無章。在我們的 HTML 中,我們將每個巢狀的元素都以兩個空格縮排。原始碼的排版風格(如要用多少空格進行縮排),可依照個人喜好使用,但你的排版方式應該要一致。

+ +

實體參照(Entity references): 引用 HTML 中的特殊字元

+ +

在 HTML 中, < 、 > 、 " 、 ' 和 & 是特殊字元,它們是 HTML 語法的一部份。那麼,要如何使用這些特殊字元呢?比方說,你如果想要用 & (ampersand)或小於符號  < (less than sign) 時,要如何避免它們被瀏覽器當成原始碼呢?

+ +

這時候我們就需要用到字元參照(character references),它們是用來表示特殊字元的編碼,專門用在這種情形上。每個字元參照都是以 & (ampersand) 起頭,以分號 ; (semi-colon) 做結。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
字元相應的字元引用
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
+ +

如果你英文不錯的話,應該不難發現字元參照其實就是這些字元的英文縮寫,也就是說,"&lt;" 為 less than (小於);"&gt;" 為 great than (大於);"&quot;" 為 quotation (引號);"&apos;" 為 apostrophe (單引號);"&amp;" 為 ampersand (和號)。你可以透過下面的維基連結來查看 HTML 的字元實體參照。在下面的範例中,你可以看到兩段敘述網頁技術的段落:

+ +
<p>In HTML, you define a paragraph using the <p> element.</p>
+
+<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
+ +

看到下面的輸出結果,你會發現第一個段落是錯誤的,因為瀏覽器認為第二個 <p> 是要開啟新段落。而第二個段落就沒問題,因為我們將 < 及 > 換成了字元參照。

+ +

{{ EmbedLiveSample('實體參照Entity_references_引用_HTML_中的特殊字元', 700, 200, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: 你可以在維基百科中找到完整的 HTML 字元實體參照的對照表: List of XML and HTML character entity references。請記得只要你的 HTML 的字元編碼設定為 UTF-8,你就不需要使用其他字元的實體參照,因為現今的瀏覽器都能應付。

+
+ +

HTML 註解

+ +

HTML 就像大部分的程式語言,提供了一種能讓我們可以在原始碼中加入註解的方式 — 註解是會被瀏覽器忽略,並且不會被使用者看到的,它們存在的目的是要讓你得以在原始碼中說明你的原始碼是如何運作的、每段原始碼的作用等等。當你已經六個月沒有察看某個網頁的原始碼,而你完全想不起來你做了什麼的時候、或是當你把你的原始碼交給別人一同協作時,註解將會是你的好朋友!

+ +

試著將你 HTML 檔案中的一部份內容變成註解,你需要將內容包裹在特殊的符號 <!-- 和 -->之中,例如:

+ +
<p>I'm not inside a comment</p>
+
+<!-- <p>I am!</p> -->
+ +

如你所見,在下方的範例中,第一個段落出現在輸出結果中,但第二個段落並沒有出現。

+ +

{{ EmbedLiveSample('HTML_註解', 700, 100) }}

+ +

總結

+ +

恭喜你看完了這個章節,我們你能享受這個學習基礎 HTML 的旅程!目前,你應該已經了解 HTML 長什麼樣子、它最基本的運作方式,並且能夠寫出一些元素和屬性。基礎 HTML 大致上就到這裡結束,在單元接下來的章節中,我們將會更深入探討本章節學到的內容並介紹更多 HTML 的觀念。千萬別轉台!

+ +
+

Note: 目前,在你要開始學更多有關 HTML 的知識時,你可能也想要探索基礎的 CSS(Cascading Style Sheets)。CSS 是一種用來為你的網頁增添花樣的語言,例如改變字型、顏色,或改變頁面的布局。你很快就會發現,同時使用 HTML 和 CSS 會帶來很棒的效果。

+
+ +

 另見

+ + + +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

在本主題中的內容

+ + diff --git a/files/zh-tw/learn/html/introduction_to_html/html_text_fundamentals/index.html b/files/zh-tw/learn/html/introduction_to_html/html_text_fundamentals/index.html new file mode 100644 index 0000000000..fc0e2eff89 --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/html_text_fundamentals/index.html @@ -0,0 +1,953 @@ +--- +title: 基本 HTML 文字 +slug: Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals +translation_of: Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML")}}
+ +

HTML 的其中一件核心工作,就是給出文件的結構和含義(又稱{{glossary("semantics")}}),以便瀏覽器正確顯示。本文章旨在說明 {{glossary("HTML")}} 可透過增加標題、章節、強調、建立清單等,建立結構化的頁面。

+ + + + + + + + + + + + +
需求:熟悉基本 HTML、在 Getting started with HTML 有講解。
目標:學習如何標記一個具有文字的基礎頁面賦予它結構及含義— 包含段落, 標題, 列表, 強調文字, 以及引用句
+ +

基本:標題與段落

+ +

多數結構化的文字由標題及段落構成,不論你是在閱讀故事,翻閱報紙,讀教科書,翻閱雜誌,等等。

+ +

An example of a newspaper front cover, showing use of a top level heading, subheadings and paragraphs.

+ +

充滿結構性的文字內容讓閱讀經驗變得輕鬆且更加愉悅。

+ +

在HTML裡,每個段落都被包在 {{htmlelement("p")}} 元素中,就像:

+ +
<p>I am a paragraph, oh yes I am.</p>
+ +

而每個標題需要被包在標題元素中:

+ +
<h1>I am the title of the story.</h1>
+ +

在HTML裡有六種標題元素:{{htmlelement("h1")}}, {{htmlelement("h2")}}, {{htmlelement("h3")}}, {{htmlelement("h4")}}, {{htmlelement("h5")}},跟 {{htmlelement("h6")}}. 每個元素分別代表著在文件中的不同層級; <h1> 代表主標題, <h2> 代表副標題, <h3> 代表更次級的副標題, 依此類推。

+ +

實作架構化階層

+ +

舉例來說,在一個故事裡,<h1> 將用來代表整個故事的標題,<h2> 則代表每個章節的標題,而<h3> 代表每個章節中的副標題,依此類推下去。

+ +
<h1>The Crushing Bore</h1>
+
+<p>By Chris Mills</p>
+
+<h2>Chapter 1: The dark night</h2>
+
+<p>It was a dark night. Somewhere, an owl hooted. The rain lashed down on the ...</p>
+
+<h2>Chapter 2: The eternal silence</h2>
+
+<p>Our protagonist could not so much as a whisper out of the shadowy figure ...</p>
+
+<h3>The specter speaks</h3>
+
+<p>Several more hours had passed, when all of a sudden the specter sat bolt upright and exclaimed, "Please have mercy on my soul!"</p>
+ +

只要層次結構有意義,要一個元件顯示什麼取決於你。當你在建立類似的文字結構時,只要記得以下幾點:

+ + + +

為何我們需要架構?

+ +

為了回答這個問題。我們先看看 text-start.html 這個文章(鷹嘴豆泥食譜)的最前端。請先下載這個文件的副本到你的電腦,等一下練習時會用到。這個文件目前包含很多不同的內容,並沒有被標記出架構,唯一的排版只有換行而已。

+ +

所以當你在瀏覽器中打開這份文件時,你將會看到這些文字看起來擠成一團!

+ +

A webpage that shows a wall of unformatted text, because there are no elements on the page to structure it.

+ +

這是因為文件內沒有元素去標示出文件的架構,所以瀏覽器不知道怎麼排版。此外:

+ + + +

以上原因說明為何我們要為內容標示出架構。

+ +

Active learning: Giving our content structure

+ +

Let's jump straight in with a live example. In the example below, add elements to the raw text in the Input field so that it appears as a heading and two paragraphs in the Output field.

+ +

If you make a mistake, you can always reset it using the Reset button. 如果你中途卡關,點擊按鈕來查看答案

+ + + +

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

+ +

Why do we need semantics?

+ +

Semantics are relied on everywhere around us — we rely on previous experience to tell us what the function of an everyday object is; when we see something, we know what its function will be. So, for example, we expect a red traffic light to mean "stop", and a green traffic light to mean "go". Things can get tricky very quickly if the wrong semantics are applied (Do any countries use red to mean "go"? I hope not.)

+ +

In a similar vein, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance. In this context the {{htmlelement("h1")}} element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page."

+ +
<h1>This is a top level heading</h1>
+ +

By default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using CSS). More importantly, its semantic value will be used in multiple ways, for example by search engines and screen readers (as mentioned above).

+ +

On the other hand, you could make any element look like a top level heading. Consider the following:

+ +
<span style="font-size: 32px; margin: 21px 0; display: block;">Is this a top level heading?</span>
+ +

This is a {{htmlelement("span")}} element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with JavaScript) without giving it any extra meaning (you'll find out more about these later on in the course). We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job.

+ +

Lists

+ +

Now let's turn our attention to lists. Lists are everywhere in life — from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! Lists are everywhere on the Web too, and we've got three different types to worry about.

+ +

Unordered

+ +

Unordered lists are used to mark up lists of items for which the order of the items doesn't matter — let's take a shopping list as an example.

+ +
milk
+eggs
+bread
+hummus
+ +

Every unordered list starts off with a {{htmlelement("ul")}} element — this wraps around all the list items:

+ +
<ul>
+milk
+eggs
+bread
+hummus
+</ul>
+ +

The last step is to wrap each list item in a {{htmlelement("li")}} (list item) element:

+ +
<ul>
+  <li>milk</li>
+  <li>eggs</li>
+  <li>bread</li>
+  <li>hummus</li>
+</ul>
+ +

Active learning: Marking up an unordered list

+ +

Try editing the live sample below to create your very own HTML unordered list.

+ + + +

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

+ +

Ordered

+ +

Ordered lists are lists in which the order of the items does matter — let's take a set of directions as an example:

+ +
Drive to the end of the road
+Turn right
+Go straight across the first two roundabouts
+Turn left at the third roundabout
+The school is on your right, 300 meters up the road
+ +

The markup structure is the same as for unordered lists, except that you have to wrap the list items in an {{htmlelement("ol")}} element, rather than <ul>:

+ +
<ol>
+  <li>Drive to the end of the road</li>
+  <li>Turn right</li>
+  <li>Go straight across the first two roundabouts</li>
+  <li>Turn left at the third roundabout</li>
+  <li>The school is on your right, 300 meters up the road</li>
+</ol>
+ +

Active learning: Marking up an ordered list

+ +

Try editing the live sample below to create your very own HTML ordered list.

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Active learning: Marking up our recipe page

+ +

So at this point in the article, you have all the information you need to mark up our recipe page example. You can choose to either save a local copy of our text-start.html starting file and do the work there, or do it in the editable example below. Doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page. Both have pros and cons.

+ + + +

{{ EmbedLiveSample('Playable_code_4', 900, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

If you get stuck, you can always press the Show solution button, or check out our text-complete.html example on our github repo.

+ +

Nesting lists

+ +

It is perfectly ok to nest one list inside another one. You might want to have some sub-bullets sitting below a top level bullet. Let's take the second list from our recipe example:

+ +
<ol>
+  <li>Remove the skin from the garlic, and chop coarsely.</li>
+  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
+  <li>Add all the ingredients into a food processor.</li>
+  <li>Process all the ingredients into a paste.</li>
+  <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
+  <li>If you want a smooth hummus, process it for a longer time.</li>
+</ol>
+ +

Since the last two bullets are very closely related to the one before them (they read like sub-instructions or choices that fit below that bullet), it might make sense to nest them inside their own unordered list, and put that list inside the current fourth bullet. This would look like so:

+ +
<ol>
+  <li>Remove the skin from the garlic, and chop coarsely.</li>
+  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
+  <li>Add all the ingredients into a food processor.</li>
+  <li>Process all the ingredients into a paste.
+    <ul>
+      <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
+      <li>If you want a smooth hummus, process it for a longer time.</li>
+    </ul>
+  </li>
+</ol>
+ +

Try going back to the previous active learning example and updating the second list like this.

+ +

Emphasis and importance

+ +

In human language, we often emphasise certain words to alter the meaning of a sentence, and we often want to mark certain words as important or different in some way. HTML provides various semantic elements to allow us to mark up textual content with such effects, and in this section, we'll look at a few of the most common ones.

+ +

Emphasis

+ +

When we want to add emphasis in spoken language, we stress certain words, subtly altering the meaning of what we are saying. Similarly, in written language we tend to stress words by putting them in italics. For example, the following two sentences have different meanings.

+ +

I am glad you weren't late.

+ +

I am glad you weren't late.

+ +

The first sentence sounds genuinely relieved that the person wasn't late. In contrast, the second one sounds sarcastic or passive-aggressive, expressing annoyance that the person arrived a bit late.

+ +

In HTML we use the {{htmlelement("em")}} (emphasis) element to mark up such instances. As well as making the document more interesting to read, these are recognised by screen readers and spoken out in a different tone of voice. Browsers style this as italic by default, but you shouldn't use this tag purely to get italic styling. To do that, you'd use a {{htmlelement("span")}} element and some CSS, or perhaps an {{htmlelement("i")}} element (see below).

+ +
<p>I am <em>glad</em> you weren't <em>late</em>.</p>
+ +

Strong importance

+ +

To emphasize important words, we tend to stress them in spoken language and bold them in written language. For example:

+ +

這液體具有相當強的毒性

+ +

我相信你。千萬別遲到了!

+ +

In HTML we use the {{htmlelement("strong")}} (strong importance) element to mark up such instances. As well as making the document more useful, again these are recognized by screen readers and spoken in a different tone of voice. Browsers style this as bold text by default, but you shouldn't use this tag purely to get bold styling. To do that, you'd use a {{htmlelement("span")}} element and some CSS, or perhaps a {{htmlelement("b")}} element (see below).

+ +
<p>This liquid is <strong>highly toxic</strong>.</p>
+
+<p>I am counting on you. <strong>Do not</strong> be late!</p>
+ +

You can nest strong and emphasis inside one another if desired:

+ +
<p>This liquid is <strong>highly toxic</strong> —
+if you drink it, <strong>you may <em>die</em></strong>.</p>
+ +

Active learning: Let's be important!

+ +

In this active learning section, we have provided an editable example. Inside it, we'd like you to try adding emphasis and strong importance to the words you think need them, just to have some practice.

+ + + +

{{ EmbedLiveSample('Playable_code_5', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Italic, bold, underline...

+ +

The elements we've discussed so far have clearcut associated semantics. The situation with {{htmlelement("b")}}, {{htmlelement("i")}}, and {{htmlelement("u")}} is somewhat more complicated. They came about so people could write bold, italics, or underlined text in an era when CSS was still supported poorly or not at all. Elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used, because as we've seen before, semantics is so important to accessibility, SEO, etc.

+ +

HTML5 redefined <b>, <i> and <u> with new, somewhat confusing, semantic roles.

+ +

Here's the best rule of thumb: it's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. However, it always remains critical to keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet.

+ + + +
+

A kind warning about underline: People strongly associate underlining with hyperlinks. Therefore, on the Web, it's best to underline only links. Use the <u> element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the Web. The example below illustrates how it can be done.

+
+ +
<!-- scientific names -->
+<p>
+  The Ruby-throated Hummingbird (<i>Archilochus colubris</i>)
+  is the most common hummingbird in Eastern North America.
+</p>
+
+<!-- foreign words -->
+<p>
+  The menu was a sea of exotic words like <i lang="uk-latn">vatrushka</i>,
+  <i lang="id">nasi goreng</i> and <i lang="fr">soupe à l'oignon</i>.
+</p>
+
+<!-- a known misspelling -->
+<p>
+  Someday I'll learn how to <u style="text-decoration-line: underline; text-decoration-style: wavy;">spel</u> better.
+</p>
+
+<!-- Highlight keywords in a set of instructions -->
+<ol>
+  <li>
+    <b>Slice</b> two pieces of bread off the loaf.
+  </li>
+  <li>
+    <b>Insert</b> a tomato slice and a leaf of
+    lettuce between the slices of bread.
+  </li>
+</ol>
+ +

總結

+ +

That's it for now! This article should have given you a good idea of how to start marking up text in HTML, and introduced you to some of the most important elements in this area. There are a lot more semantic elements to cover in this area, and we'll look at a lot more in our 'More Semantic Elements' article, later on in the course. In the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the Web.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/html/introduction_to_html/index.html b/files/zh-tw/learn/html/introduction_to_html/index.html new file mode 100644 index 0000000000..47c9f80769 --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/index.html @@ -0,0 +1,61 @@ +--- +title: HTML介紹 +slug: Learn/HTML/Introduction_to_HTML +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

本質上,{{glossary("HTML")}} 是一種非常簡單的語言,由元素所組成。元素可以賦予文字片段不同的意義 (比方說,將它們描述成段落、項目清單,或是表格的一部分)、將文件組織成不同的邏輯區段 (如標頭(header)、三行的內文,或是導覽目錄),以及在網頁中嵌入圖片或影片等內容。在這個主題中我們將介紹前面兩項,並介紹基本概念以及語法以讓你了解 HTML。

+ +

預備知識

+ +

在開始閱讀之前,你並不需要具備任何 HTML 知識,你只要能夠操作電腦、瀏覽網頁並消化其中的內容即可。你需要建立一個基礎工作環境,並且了解如何建立與管理檔案──這些都屬於我們 Web 入門 的一部分。

+ +
+

提示: 如果您是在某些無法建立個人檔案的電腦/平板/其他裝置上進行,您可以在一些線上 coding program (如 JSBinThimble) 上測試程式碼範例。

+
+ +

導覽

+ +

這個主題包含以下子題,將帶你了解所有 HTML 的基礎理論,並且提供充足的機會讓你測試所習得的技能。

+ +
+
HTML 入門
+
包含 HTML 最基礎的部分──我們將定義元素(elements)、屬性(attributes)以及其他重要術語,並且介紹它們的使用方法。除此之外,我們也將說明典型的 HTML 網頁及其中的元素是如何構成的,並解釋其他重要的基本語言特性。還有,我們也會玩一些 HTML,好引發你的興趣!
+
在 head 中有什麼? HTML 中的後設資料(Metadata)
+
HTML 文件的 head 是在網頁加載完畢之後,不會顯示在瀏覽器上的部分。其中包含一些資訊,如頁面的標題({{htmlelement("title")}})、{{glossary("CSS")}} 的連結 (當你想利用 CSS 來妝點你的頁面 HTML 時,你會用到它們)、網頁圖示(favicon)的連結,以及 metadata (裡頭承載了有關於該 HTML 的資料,如作者、描述該文件的關鍵詞等。)
+
HTML 文字的基礎知識
+
一個 HTML 的主要作用是賦予純文字意義(又稱為語義化),好讓瀏覽器知道如何正確地顯示它。這篇文章將探討如何使用 HTML 來將文字區塊拆解為標題(heading)和段落(paragraph)、強調字詞、建立列表等等。
+
建立超連結
+
超連結真的非常重要 — 它造就了我們現今所知的網路。這篇文章介紹超連結的使用語法,並且探討建立連結的最佳實踐方法。
+
進階文字格式
+
在 HTML 中還有許多可以用來格式化文字的元素,但我們沒有在 HTML 文字的基礎知識中提及這些內容。雖然這些元素比較鮮為人知,不過還是相當值得一談。在這篇文章中,你將會學到如何表示引言、描述列表、程式碼、上下標,及聯繫訊息等等。 
+
文件與網站架構
+
除了分別定義網頁的各個成分(例如:段落或是圖片),HTML 還能定義網頁上的區塊(例如:標頭、導航列或是主要內容)。這篇文章將介紹如何規劃一個基本的網頁架構,以及如何透過編寫 HTML 來表示網頁架構。
+
HTML 除錯
+
如果 HTML 出錯了,卻找不到哪裡有錯誤該怎麼辦?這篇文章將會介紹一些能幫得上忙的實用工具。
+
+ +

評量

+ +

下面的評量將測試您對於以上的 HTML 基礎是否已經了解。

+ +
+
標記信件內容
+
我們都學過怎麼寫信,而信件也是用來測試我們格式化文字技巧的好例子。在這份測驗中,你將需要以 HTML 將一封信標記成題目要求的樣子。
+
組織網頁內容
+
這份測驗將要測試你利用 HTML 來組織網頁的能力,該網頁將包含頁眉(header)、頁腳(footer)、導覽列(navigation)、內文(main content)和側邊攔(sidebar)。
+
+ +

另見

+ +
+
Web literacy basics 1
+
Mozilla 基金會所提供的一個優質課程。該課程探索並測驗了很多在本主題中所提及的技術。透過裡頭的六大學習主題,學習者能夠熟悉閱讀、撰寫以及參與網路,並經由實作與合作了解網路基礎。
+
+ +
+

回饋

+ +

請填寫問卷以協助改善我們的導覽與教學。

+
diff --git a/files/zh-tw/learn/html/introduction_to_html/the_head_metadata_in_html/index.html b/files/zh-tw/learn/html/introduction_to_html/the_head_metadata_in_html/index.html new file mode 100644 index 0000000000..db41ab4ec4 --- /dev/null +++ b/files/zh-tw/learn/html/introduction_to_html/the_head_metadata_in_html/index.html @@ -0,0 +1,261 @@ +--- +title: What’s in the head? Metadata in HTML +slug: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML +tags: + - 初學者 +translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}
+ +

HTML 文件的 {{glossary("Head", "head")}} 是網頁在加載完畢之後,不會顯示在瀏覽器上的部分。其中包含一些資訊,如頁面的標題({{htmlelement("title")}})、{{glossary("CSS")}} 的連結 (當你想利用 CSS 來妝點你的頁面 HTML 時,你會用到它們)、網頁圖示(favicon)的連結,以及 metadata (裡頭承載了有關於該 HTML 的資料,如作者、描述該文件的關鍵詞等)。在這一章節裡,我們會討論以上的內容,甚至更多,藉此替你打下標記網頁的根基。

+ + + + + + + + + + + + +
需求:對 HTML 的基礎認識,內容我們已在 HTML 入門中提及。
目標:學習 HTML 的 head,了解它的目的、它能包含什麼重要東西,以及它對 HTML 文件產生的影響。
+ +

什麼是 HTML head?

+ +

讓我們再看一次之前所看過的 HTML 文件

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

HTML 的 head 就是 {{htmlelement("head")}} 元素裡面的內容 — 跟 {{htmlelement("body")}} 元素中的內容不同(當網頁被載入瀏覽器中時,會呈現在頁面上),head 裡的內容不會顯示在頁面上,它的任務是要容納文件的 {{glossary("Metadata", "metadata")}}。在上例中,head 只有這樣:

+ +
<head>
+  <meta charset="utf-8">
+  <title>My test page</title>
+</head>
+ +

假如換作是較大型的網頁,head 裡面可能就會有非常多東西了。現在你可以先到幾個你常去的網站,並利用開發者工具來檢視它們的 head。我們在這裡並不打算要向你展示所有能放在 head 中的東西,而是教你使用一些常用的元素,讓你熟悉熟悉它們。總而言之,讓我們開始吧!

+ +

加入標題(title)

+ +

我們已經看到活生生的 {{htmlelement("title")}} 元素了 — 這東西就是用來為文件加上標題的。你可能會把它跟 {{htmlelement("h1")}} 搞混,{{htmlelement("h1")}} 是用來為網頁主體加上標題的元素,有時也被叫做頁面標題 (page title),雖然聽起來功能很像,但他們是不同的東西!

+ + + +

不要光是看:檢視一個簡單的範例

+ +
    +
  1. 在開始這次主動學習之前,請你先到我們的 GitHub repo 中下載一份 title-example.html page。要做到這件事情,你可以: + +
      +
    1. 用你的文字編輯器開一個新檔案,並將原始碼複製到裡面,然後再儲存在一個合適的地方。
    2. +
    3. 按下網頁上的 Raw 按鈕,它就會將原始碼以純文字的形式顯示在你瀏覽器的新分頁上。接著點按右鍵,將檔案儲存在你喜歡的地方。
    4. +
    +
  2. +
  3. 現在在你的瀏覽器中開啟檔案,你看到的東西應該會長這樣: +

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.這樣子你應該可以很清楚地看到哪裡是 <h1>,而哪裡是 <title> 了!

    +
  4. +
  5. 試著開啟文字編輯器,修改兩元素的內容,儲存後再重整網頁,看看有什麼不同。
  6. +
+ +

<title> 元素中的內容也被用在其他地方。舉個例子,如果你想要收藏這個網頁,(在 Firefox 上是 書籤 > 將本頁加入書籤 或按下 URL 列的星星符號),你就會看到 <title> 的內容被設為建議的書籤名稱。

+ +

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

+ +

接下來你就會看到,<title> 的內容也會被用在搜尋當中。

+ +

Metadata: <meta> 元素

+ +

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

+ +

指定文件字元編碼

+ +

In the example we saw above, this line was included:

+ +
<meta charset="utf-8">
+ +

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

+ +

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

+ +

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

+ +

Active learning: Experiment with character encoding

+ +

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

+ +
<p>Japanese example: ご飯が熱い。</p>
+ +

加入作者(author)和描述(description)

+ +

Many <meta> elements include name and content attributes:

+ + + +

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

+ +
<meta name="author" content="Chris Mills">
+<meta name="description" content="The MDN Learning Area aims to provide
+complete beginners to the Web with all they need to know to get
+started with developing web sites and applications.">
+ +

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

+ +

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

+ +

Active learning: The description's use in search engines

+ +

The description is also used on search engine result pages. Let's go through an exercise to explore this

+ +
    +
  1. Go to the front page of The Mozilla Developer Network.
  2. +
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. +
  5. Find the description meta tag. It will look like this: +
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    +information about Open Web technologies including HTML, CSS, and APIs for both
    +Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    +
  6. +
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! +

    A Yahoo search result for "Mozilla Developer Network"

    +
  8. +
+ +
+

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

+
+ +
+

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

+
+ +

其他種類的metadata

+ +

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

+ +

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

+ +
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
+<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
+information about Open Web technologies including HTML, CSS, and APIs for both Web sites
+and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
+<meta property="og:title" content="Mozilla Developer Network">
+ +

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

+ +

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

+ +
<meta name="twitter:title" content="Mozilla Developer Network">
+ +

加入屬於自己的網頁icon

+ +

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

+ +

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

+ +

A favicon can be added to your page by:

+ +
    +
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. +
  3. Adding the following line into your HTML <head> to reference it: +
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    +
  4. +
+ +

Here is an example of a favicon in a bookmarks panel:

+ +

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

+ +

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

+ +
<!-- third-generation iPad with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
+<!-- iPhone with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
+<!-- first- and second-generation iPad: -->
+<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
+<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
+<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
+<!-- basic favicon -->
+<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
+ +

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

+ +

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

+ +

在HTML中加入CSS和JavaScript

+ +

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

+ + + +

Active learning: applying CSS and JavaScript to a page

+ +
    +
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. +
  3. Open the HTML file in both your browser, and your text editor.
  4. +
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. +
+ +

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

+ +

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

+ + + +
+

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

+
+ +

預設文件語言

+ +

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

+ +
<html lang="en-US">
+ +

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

+ +

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

+ +
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
+ +

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

+ +

總結

+ +

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

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" new file mode 100644 index 0000000000..5a2dfd7eff --- /dev/null +++ "b/files/zh-tw/learn/html/multimedia_and_embedding/html\344\270\255\347\232\204\345\234\226\347\211\207/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/index.html b/files/zh-tw/learn/html/multimedia_and_embedding/index.html new file mode 100644 index 0000000000..05d98a462b --- /dev/null +++ b/files/zh-tw/learn/html/multimedia_and_embedding/index.html @@ -0,0 +1,53 @@ +--- +title: Multimedia and Embedding +slug: Learn/HTML/Multimedia_and_embedding +translation_of: Learn/HTML/Multimedia_and_embedding +--- +

{{LearnSidebar}}

+ +

到目前為止,我們已經看到了很多文字,但是只使用文字讓人感到無聊。讓我們開始研究如何透過更有趣的內容讓網絡變得活躍起來!本單元探討如何使用HTML在您的網頁中包增加媒體,包括可以嵌入圖像的不同方式,以及如何嵌入影片,音訊甚至整個網頁。

+ +

預備知識

+ +

在此單元開始之前,我們假設你對HTML基礎知識 (如HTML介紹) 已經有一定的了解,如果還沒有,建議您先預習該部分再回來。

+ +
+

Note: 如果你所操作的電腦、平板或裝置環境不允許你建立自己的檔案,你可以在諸如 JSBin 或Thimble 這樣的網站上嘗試(多數的)範例程式碼。

+
+ +

導覽

+ +

本單元包含以下章節,它們將帶您了解在網頁上嵌入多媒體的所有基礎知識。

+ +
+
HTML中的圖片
+
可以考慮到的多媒體種類很多,但是從用以將簡單圖像嵌入網頁中不起眼的{{htmlelement(" img")}}元素開始是很合乎邏輯的。在本文中,我們將研究如何更深入地使用它,包括基礎知識,使用{{htmlelement("figure")}}加上標題的註釋以及它與CSS背景圖像的關係。
+
視訊與音訊內容
+
接著,我們將研究如何使用HTML5 {{htmlelement("video")}}和{{htmlelement("audio")}} 元素在頁面上嵌入視訊和音訊,包括基本知識,以提供對不同頁面的訪問文件格式添加到不同的瀏覽器,添加標題和字幕,以及如何為舊版瀏覽器添加後備廣告。
+
從物件到 iframe — 其他嵌入技巧
+
在這裡,我們想橫跨一步,著眼於幾個元素,這些元素可以使您將各種內容類型嵌入到網頁中:{{htmlelement("iframe")}},{{htmlelement("embed")}}和 {{htmlelement("object")}}元素。 <iframe>用於嵌入其他網頁,另外兩個允許您嵌入PDF,SVG甚至Flash(一種即將消逝的技術,但您可能仍會定期看到它)。
+
為 Web 新增向量圖
+
向量圖形在某些情況下可能非常有用。 與PNG / JPG等常見格式不同,它們在放大時不會失真/像素化-在縮放時可以保持平滑。 本文向您介紹什麼是向量圖,以及如何在網頁中加入流行的{{glossary("SVG")}}格式。
+
適應性圖片
+
在本文中,我們將學習適應性圖片 (又稱響應式圖片)的概念。適應性圖片在不同螢幕尺寸,解析度和其他類似功能差異很大的設備上都能很好地運作。我們還會研究HTML提供了哪些工具來幫助實現它們。 這有助於提高不同設備之間的性能。 響應式圖片只是響應式設計的一部分,在將來您學習CSS的單元中還會有響應式圖片的單元。
+
+ +

評量

+ +

以下評量中將測試您對以上指南中介紹的HTML基礎的理解:

+ +
+
Mozilla 啟動頁面
+
在此測驗中,我們將測試您對本區塊文章中討論的一些技術的了解,使您能夠向時髦的啟動頁面添加有關Mozilla的一些圖片和視訊!
+
+ +

另見

+ +
+
增加點擊映射到圖片上層
+
圖像映射提供了一種機制,可以使圖像的不同部分鏈接到不同的位置。(請試想在地圖上點擊每個不同國家/地區以取得更多資訊)此技術有時很有用。
+
網頁知識基礎2
+
+

一個出色的Mozilla基礎課程,探索和測試此多媒體和嵌入單元中討論的一些技能。 深入研究網頁組成,可訪問性設計,共享資源,使用線上媒體和開放性工作的基礎知識(這意味著您的內容可以免費獲得併可以由他人共享)。

+
+
diff --git a/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/index.html b/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/index.html new file mode 100644 index 0000000000..aa4de14fe3 --- /dev/null +++ b/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/index.html @@ -0,0 +1,339 @@ +--- +title: Video and audio content +slug: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content +tags: + - Article + - Audio + - Beginner + - Guide + - HTML + - NeedsTranslation + - TopicStub + - Video + - captions + - subtitles + - track +translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
+ +

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

+ + + + + + + + + + + + +
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 Images in HTML.
Objective:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
+ +

Video and audio on the web

+ +

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

+ +

A native solution would solve much of this if implemented correctly. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

+ +

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

+ +
+

Note: Before you begin here, you should also know that there are quite a few OVPs (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages; if you use that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

+
+ +

The <video> element

+ +

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

+ +
<video src="rabbit320.webm" controls>
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
+</video>
+ +

The features of note are:

+ +
+
{{htmlattrxref("src","video")}}
+
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
+
{{htmlattrxref("controls","video")}}
+
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At a minimum, the interface must include a way to start and stop the media, and to adjust the volume.
+
The paragraph inside the <video> tags
+
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case, we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
+
+ +

The embedded video will look something like this:

+ +

A simple video player showing a video of a small white rabbit

+ +

You can try the example live here (see also the source code.)

+ +

Using multiple source formats to improve compatibility

+ +

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with an older browser like Internet Explorer or even an older version of Safari. The video won't play, because different browsers support different video (and audio) formats. Fortunately, there are things you can do to help prevent this from being a problem.

+ +

Contents of a media file

+ +

First, let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They define a structure in which the audio and/or video tracks that make up the media are stored, along with metadata describing the media, what codecs are used to encode its channels, and so forth.

+ +

A WebM file containing a movie which has a main video track and one alternate angle track, plus audio for both English and Spanish, in addition to audio for an English commentary track can be conceptualized as shown in the diagram below. Also included are text tracks containing closed captions for the feature film, Spanish subtitles for the film, and English captions for the commentary.

+ +

Diagram conceptualizing the contents of a media file at the track level.

+ +

The audio and video tracks within the container hold data in the appropriate format for the codec used to encode that media. Different formats are used for audio tracks versus video tracks. Each audio track is encoded using an audio codec, while video tracks are encoded using (as you probably have guessed) a video codec. As we talked about before, different browsers support different video and audio formats, and different container formats (like MP3, MP4, and WebM, which in turn can contain different types of video and audio).

+ +

For example:

+ + + +

There are some special cases. For example, for some types of audio, a codec's data is often stored without a container, or with a simplified container. One such instance is the FLAC codec, which is stored most commonly in FLAC files, which are just raw FLAC tracks.

+ +

Another such situation is the always-popular MP3 file. An "MP3 file" is actually an MPEG-1 Audio Layer III (MP3) audio track stored within an MPEG or MPEG-2 container. This is especially interesting since while most browsers don't support using MPEG media in the {{HTMLElement("video")}} and {{HTMLElement("audio")}} elements, they may still support MP3 due to its popularity.

+ +

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

+ +

Media file support in browsers

+ +
+

Why do we have this problem? It turns out that several popular formats, such as MP3 and MP4/H.264, are excellent but are encumbered by patents; that is, there are patents covering some or all of the technology that they're based upon. In the United States, patents covered MP3 until 2017, and H.264 is encumbered by patents through at least 2027.

+ +

Because of those patents, browsers that wish to implement support for those codecs must pay typically enormous license fees. In addition, some people simply prefer to avoid restricted software and prefer to use only open formats. Due to these legal and preferential reasons, web developers find themselves having to support multiple formats to capture their entire audience.

+
+ +

The codecs described in the previous section exist to compress video and audio into manageable files, since raw audio and video are both exceedingly large. Each web browser supports an assortment of {{Glossary("Codec","codecs")}}, like Vorbis or H.264, which are used to convert the compressed audio and video into binary data and back. Each codec offers its own advantages and drawbacks, and each container may also offer its own positive and negative features affecting your decisions about which to use.

+ +

Things become slightly more complicated because not only does each browser support a different set of container file formats, they also each support a different selection of codecs. In order to maximize the likelihood that your web site or app will work on a user's browser, you may need to provide each media file you use in multiple formats. If your site and the user's browser don't share a media format in common, your media simply won't play.

+ +

Due to the intricacies of ensuring your app's media is viewable across every combination of browsers, platforms, and devices you wish to reach, choosing the best combination of codecs and container can be a complicated task. See {{SectionOnPage("/en-US/docs/Web/Media/Formats/Containers", "Choosing the right container")}} for help selecting the container file format best suited for your needs; similarly, see {{SectionOnPage("/en-US/docs/Web/Media/Formats/Video_codecs", "Choosing a video codec")}} and {{SectionOnPage("/en-US/docs/Web/Media/Formats/Audio_codecs", "Choosing an audio codec")}} for help selecting the first media codecs to use for your content and your target audience.

+ +

One additional thing to keep in mind: mobile browsers may support additional formats not supported by their desktop equivalents, just like they may not support all the same formats the desktop version does. On top of that, both desktop and mobile browsers may be designed to offload handling of media playback (either for all media or only for specific types it can't handle internally). This means media support is partly dependent on what software the user has installed.

+ +

So how do we do this? Take a look at the following updated example (try it live here, also):

+ +
<video controls>
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+ +

Here we've taken the src attribute out of the actual {{HTMLElement("video")}} tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the {{HTMLElement("source")}} elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

+ +

Each <source> element also has a {{htmlattrxref("type", "source")}} attribute. This is optional, but it is advised that you include it. The type attribute contains the {{glossary("MIME type")}} of the file specified by the <source>, and browsers can use the type to immediately skip videos they don't understand. Iftype isn't included, browsers will load and try to play each file until they find one that works, which obviously takes time and is an unnecessary use of resources.

+ +

Refer to our guide to media types and formats for help selecting the best containers and codecs for your needs, as well as to look up the right MIME types to specify for each.

+ +

Other <video> features

+ +

There are a number of other features you can include when displaying an HTML video. Take a look at our next example:

+ +
<video controls width="400" height="400"
+       autoplay loop muted preload="auto"
+       poster="poster.png">
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+
+ +

The resulting UI looks something like this:

+ +

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!

+ +

The new features are:

+ +
+
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
+
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
+
{{htmlattrxref("autoplay","video")}}
+
Makes the audio or video start playing right away, while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
+
{{htmlattrxref("loop","video")}}
+
Makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
+
{{htmlattrxref("muted","video")}}
+
Causes the media to play with the sound turned off by default.
+
{{htmlattrxref("poster","video")}}
+
The URL of an image which will be displayed before the video is played. It is intended to be used for a splash screen or advertising screen.
+
{{htmlattrxref("preload","video")}}
+
+

Used for buffering large files; it can take one of three values:

+ +
    +
  • "none" does not buffer the file
  • +
  • "auto" buffers the media file
  • +
  • "metadata" buffers only the metadata for the file
  • +
+
+
+ +

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

+ +

The <audio> element

+ +

The {{htmlelement("audio")}} element works just like the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

+ +
<audio controls>
+  <source src="viper.mp3" type="audio/mp3">
+  <source src="viper.ogg" type="audio/ogg">
+  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
+</audio>
+ +

This produces something like the following in a browser:

+ +

A simple audio player with a play button, timer, volume control, and progress bar

+ +
+

Note: You can run the audio demo live on Github (also see the audio player source code.)

+
+ +

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML video are as follows:

+ + + +

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

+ +

Restarting media playback (requires JavaScript)

+ +

At any time, you can reset the media to the beginning—including the process of selecting the best media source, if more than one is specified using {{HTMLElement("source")}} elements—by calling the element's {{domxref("HTMLMediaElement.load", "load()")}} method:

+ +
const mediaElem = document.getElementById("my-media-element");
+mediaElem.load();
+ +

Detecting track addition and removal (requires JavaScript)

+ +

You can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. For example, you can watch for the {{event("addtrack")}} event being fired on the associated {{domxref("AudioTrackList")}} object (retrieved via {{domxref("HTMLMediaElement.audioTracks")}}) to be informed when audio tracks are added to the media:

+ +
const mediaElem = document.querySelector("video");
+mediaElem.audioTracks.onaddtrack = function(event) {
+  audioTrackAdded(event.track);
+}
+
+ +

You'll find more information about this in our {{domxref("TrackEvent")}} documentation.

+ +

Displaying video text tracks

+ +

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

+ + + +

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML video, you can. To do so we use the WebVTT file format and the {{htmlelement("track")}} element.

+ +
+

Note: "Transcribe" means "to write down spoken words as text." The resulting text is a "transcript."

+
+ +

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as the time in the video at which each text string should be displayed, and even limited styling/positioning information. These text strings are called cues, and there are several kinds of cues which are used for different purposes. The most common cues are:

+ +
+
subtitles
+
Translations of foreign material, for people who don't understand the words spoken in the audio.
+
captions
+
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
+
timed descriptions
+
Text which should be spoken by the media player in order to describe important visuals to blind or otherwise visually impaired users.
+
+ +

A typical WebVTT file will look something like this:

+ +
WEBVTT
+
+1
+00:00:22.230 --> 00:00:24.606
+This is the first subtitle.
+
+2
+00:00:30.739 --> 00:00:34.074
+This is the second.
+
+  ...
+
+ +

To get this displayed along with the HTML media playback, you need to:

+ +
    +
  1. Save it as a .vtt file in a sensible place.
  2. +
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. +
+ +

Here's an example:

+ +
<video controls>
+    <source src="example.mp4" type="video/mp4">
+    <source src="example.webm" type="video/webm">
+    <track kind="subtitles" src="subtitles_es.vtt" srclang="es">
+</video>
+ +

This will result in a video that has subtitles displayed, kind of like this:

+ +

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

+ +

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español.

+ +
+

Note: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

+
+ +

Active learning: Embedding your own audio and video

+ +

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily and, provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

+ +

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

+ +

We would like you to:

+ +
    +
  1. Save your audio and video files in a new directory on your computer.
  2. +
  3. Create a new HTML file in the same directory, called index.html.
  4. +
  5. Add {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements to the page; make them display the default browser controls.
  6. +
  7. Give both of them {{HTMLElement("source")}} elements so that browsers will find the audio format they support best and load it. These should include {{htmlattrxref("type", "source")}} attributes.
  8. +
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. +
+ +

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

+ +

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. Note that the third assessment question in this test assumes knowledge of some of the techniques covered in the next article, so you may want to read that before attempting it.

+ +

Summary

+ +

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/test_your_skills_colon__multimedia_and_embedding/index.html b/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/test_your_skills_colon__multimedia_and_embedding/index.html new file mode 100644 index 0000000000..951de62ef5 --- /dev/null +++ b/files/zh-tw/learn/html/multimedia_and_embedding/video_and_audio_content/test_your_skills_colon__multimedia_and_embedding/index.html @@ -0,0 +1,104 @@ +--- +title: 測試你的技能:多媒體和嵌入 +slug: >- + Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/Test_your_skills:_Multimedia_and_embedding +tags: + - HTML + - 初學者 + - 多媒體 + - 學習 + - 嵌入 + - 測驗 +translation_of: >- + Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/Test_your_skills:_Multimedia_and_embedding +--- +
{{learnsidebar}}
+ +
這項技能測試的目的是評估您是否了解我們的視訊和音訊內容以及從物件到iframe的其他嵌入技術文章。
+ +
+ +
+

Note: 您可以在下面的交互式編輯器中嘗試解決方案,但是下載代碼並使用在線工具如 CodePen, jsFiddle, or Glitch 去完成測試。
+
+ 如果您遇到困難,請向我們尋求幫助-請參閱 {{anch("Assessment or further help")}} 此頁面底部的部分。

+
+ +

多媒體和嵌入1

+ +

在此測試中,我們希望您將一個簡單的音檔嵌入到頁面上。你需要:

+ + + +

嘗試更新下面的程式碼以完成測驗:

+ +

{{EmbedGHLiveSample("learning-area/html/multimedia-and-embedding/tasks/media-embed/mediaembed1.html", '100%', 700)}}

+ +
+

下載此測驗的程式碼在你自己的編輯器或線上編輯器中運行。

+
+ +

多媒體和嵌入2

+ +

在此測驗中,我們希望你標記一個稍微複雜一些的影片播放器,此外還具有多個來源、字幕和其他功能。你需要:

+ + + +

嘗試更新下面的程式碼以完成測驗:

+ +

{{EmbedGHLiveSample("learning-area/html/multimedia-and-embedding/tasks/media-embed/mediaembed2.html", '100%', 700)}}

+ +
+

下載此測驗的程式碼在你自己的編輯器或線上編輯器中運行。

+
+ +

多媒體和嵌入3

+ +

對於此最終測驗,你需要執行兩個測驗:

+ + + +

T嘗試更新下面的程式碼以完成測驗:

+ +

{{EmbedGHLiveSample("learning-area/html/multimedia-and-embedding/tasks/media-embed/mediaembed3.html", '100%', 700)}}

+ +
+

下載此測驗的程式碼在你自己的編輯器或線上編輯器中運行。

+
+ +

評估或進一步幫助

+ +

您可以在上面的Interactive Editors中練習這些示例。

+ +

如果您希望對自己的工作進行評估,或者遇到困難希望尋求幫助:

+ +
    +
  1. 將您的工作放入在線共享編輯器中,例如 CodePen, jsFiddle, 或 Glitch. 您可以自己編寫程式碼,也可以使用以上各節中連接到的初始文件。
  2. +
  3. 撰寫帖子,要求評估和/或幫助 MDN Discourse forum Learning category. 你的貼文應包括: +
      +
    • 描述性標題,例如“ HTML圖像基礎知識1技能測試所需的評估”。
    • +
    • 您已經嘗試過的內容以及您希望我們做什麼的詳細信息,例如如果您陷入困境並需要幫助,或者需要評估。
    • +
    • 聯機共享編輯器中您要評估或需要幫助的示例的鏈接(如上面的步驟1中所述)。這是進入的好習慣-如果看不到他們的代碼,很難幫助有編碼問題的人。
    • +
    • 指向實際任務或評估頁面的鏈接,因此我們可以找到您需要幫助的問題。
    • +
    +
  4. +
+ +
+
+
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" new file mode 100644 index 0000000000..a1996f2537 --- /dev/null +++ "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" @@ -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/tables/index.html b/files/zh-tw/learn/html/tables/index.html new file mode 100644 index 0000000000..0e282b2a68 --- /dev/null +++ b/files/zh-tw/learn/html/tables/index.html @@ -0,0 +1,34 @@ +--- +title: HTML 表格 +slug: Learn/HTML/Tables +translation_of: Learn/HTML/Tables +--- +
{{LearnSidebar}}
+ +

HTML 的常見任務就是建構表格資料,某些元素與屬性正是為此目的而生。HTML 以及用於樣式化的 CSS 能方便顯示諸如讀書計劃、附近游泳池的開放時間、分析最喜歡的恐龍或足球隊……之類的表格資訊。本模塊將帶你認識建構 HTML 表格資料所需的一切。

+ +

先決條件

+ +

開始本模塊之前,你要理解基本的 HTML:請參見 HTML 介紹

+ +
+

注意:如果你用的電腦或平板之類的設備,無法允許建立自己的檔案,你可以把大部分的例子放在線上程式網站,例如 JSBinThimble

+
+ +

教學

+ +

本模塊包含以下文章:

+ +
+
HTML 表格基礎
+
這篇文章將介紹 HTML 表格,包含像是行列、標題、製作單元格、跨多行與列等基礎知識,還有如何把他們組合在一起,以方便樣式化。
+
HTML 表格進階與無障礙
+
本模塊的第二篇文章將介紹一些 HTML 表格的進階功能:例如說明、摘要、將行分成標頭、身體、還有註腳三大部分。另外,我們也會探討針對視障人士的表格無障礙。
+
+ +

評估

+ +
+
建構行星數據
+
在我們的表格評估中,我們將提供太陽系中行星的一些數據,並讓你把他們構建到 HTML 表格中。
+
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" new file mode 100644 index 0000000000..03325afbce --- /dev/null +++ "b/files/zh-tw/learn/html/tables/\345\237\272\347\244\216/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

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