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

