HTML id 屬性
HTML id
屬性用於為 HTML 元素指定一個唯一的 id。
在一個 HTML 文件中,不能有多個具有相同 id 的元素。
使用 id 屬性
The id
attribute specifies a unique id for an HTML element. The value of the id
attribute must be unique within the HTML document. (id 屬性指定一個 HTML 元素的唯一 ID。 id 屬性的值在 HTML 文件中必須是唯一的。)
The id
attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id. (id 屬性用於在樣式表中指向特定的樣式宣告。它還被 JavaScript 用於訪問和操作具有特定 id 的元素。)
id 的語法是:寫入一個井號 (#),後跟一個 id 名稱。然後,在大括號 {} 中定義 CSS 屬性。
在下面的示例中,我們有一個 <h1>
元素,它指向 id 名稱 "myHeader"。這個 <h1>
元素將根據頭部部分的 #myHeader
樣式定義進行樣式設定。
示例
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">我的標題</h1>
</body>
</html>
自己動手試一試 »
注意: ID 名稱區分大小寫!
注意: ID 名稱必須至少包含一個字元,不能以數字開頭,並且不能包含空白字元(空格、製表符等)。
Class 和 ID 之間的區別
一個 class 名稱可以被多個 HTML 元素使用,而一個 id 名稱在一個頁面中必須只能被一個 HTML 元素使用。
示例
<style>
/* 樣式化 id 為 "myHeader" 的元素 */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
/* 樣式化所有 class 名稱為 "city" 的元素 */
.city{
background-color: tomato;
color: white;
padding: 10px;
}
</style>
<!-- 具有唯一 ID 的元素 -->
<h1 id="myHeader">我的城市</h1>
<!-- 多個具有相同 class 的元素 -->
<h2 class="city">倫敦</h2>
<p>倫敦是英格蘭的首都。</p>
<h2 class="city">巴黎</h2>
<p>巴黎是法國的首都。</p>
<h2 class="city">東京</h2>
<p>東京是日本的首都。</p>
自己動手試一試 »
Tip: You can learn much more about CSS in our CSS Tutorial.
HTML 書籤(錨點)和連結
HTML 書籤用於允許讀者跳轉到網頁的特定部分。
如果你的頁面很長,書籤會很有用。
要使用書籤,你必須先建立它,然後新增一個連結到它。
然後,當點選連結時,頁面將滾動到帶有書籤的位置。
示例
首先,使用 id
屬性建立書籤
<h2 id="C4">第四章</h2>
然後,在同一頁面中,新增一個指向書籤的連結(“跳轉到第四章”)
或者,在另一個頁面中,新增一個指向書籤的連結(“跳轉到第四章”)
<a href="html_demo.html#C4">跳轉到第四章</a>
在 JavaScript 中使用 ID 屬性
The id
attribute can also be used by JavaScript to perform some tasks for that specific element. (id 屬性也可以被 JavaScript 用於為特定元素執行一些任務。)
JavaScript 可以使用 getElementById()
方法訪問具有特定 ID 的元素。
示例
使用 id
屬性透過 JavaScript 操作文字
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "祝你今天愉快!";
}
</script>
自己動手試一試 »
提示: 在 HTML JavaScript 章節或我們的 JavaScript 教程中學習 JavaScript。
Chapter Summary
- The
id
attribute is used to specify a unique id for an HTML element (id 屬性用於為 HTML 元素指定一個唯一的 id。) - The value of the
id
attribute must be unique within the HTML document (id 屬性的值在 HTML 文件中必須是唯一的。) - The
id
attribute is used by CSS and JavaScript to style/select a specific element (id 屬性被 CSS 和 JavaScript 用於樣式化/選擇特定元素。) - The value of the
id
attribute is case sensitive (id 屬性的值區分大小寫。) - The
id
attribute is also used to create HTML bookmarks (id 屬性也用於建立 HTML 書籤。) - JavaScript 可以使用
getElementById()
方法訪問具有特定 ID 的元素。
影片:HTML ID

