HTML id 是全局属性,用于唯一标识文档中的元素,允许 CSS 或 JavaScript 将其作为样式或操作目的的目标。
“id”属性在 HTML 文档中应该是唯一的,以确保正确的功能并遵守 Web 标准。在 CSS 和 Dom 方法中,id 的名称由“#”关键字引用,例如 JavaScript 中的 document.getElementById(“id_name”)。
语法
<element id = "id_name" >
id_name可以是任何东西,buut 不要在其他元素上使用相同的 id。
适用于
Id 属性是一个全局属性,这意味着几乎所有 HTML 标签都支持它。但是,像 <html>、<head> 这样的结构标签不支持 id 标签。
HTML id 属性示例
以下示例将说明 HTML id 属性,我们应该在何处以及如何使用此属性!
应用于段落的 ID 标签
在以下示例中,我们将创建一个 HTML 文档并使用 id 属性来设置元素内容的样式,如下所示:
<!DOCTYPE html>
<html>
<head>
<style>
#exciting {
background-color: orange;
border: 1px solid #696969;
padding: 10px;
border-radius: 10px;
box-shadow: 2px 2px 1px black;
}
#exciting:before {
content: 'ℹ️';
margin-right: 5px;
}
</style>
</head>
<body>
<p>
This is a Normla Text
</p>
<p id="exciting">
HTML id attribute used on this content
</p>
</body>
</html>
通过 id 属性选择元素
让我们看一下以下示例,我们将在其中运行脚本并在单击按钮时使用 id 属性更改段落的背景颜色
<!DOCTYPE html>
<html>
<body>
<p>This is a paragraph</p>
<p id="myPara">
HTML id is global attribute used to uniquely
identify an element within a document, allowing
it to be targeted by CSS or JavaScript for styling
or manipulation purposes.
</p>
<button type="button"
onclick="changeBackground()">
change background
</button>
<script>
function changeBackground() {
var para = document.getElementById("myPara");
para.style.backgroundColor = "grey";
}
</script>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |