HTML id 属性用于唯一标识 HTML 文档中的元素,从而允许有针对性的样式、脚本和链接。
此属性经常用于样式、管理事件和更改文档的结构。为了创建交互式和动态的网页,它使开发人员能够针对特定部分并为他们提供专门的行为和外观。
语法
<tag id = ‘id_name’></tag>
其中 id_name 可以是您选择的任何变量名称。
适用于
Id 属性是一个全局属性,这意味着几乎所有 HTML 标签都支持它。但是,像 <html>、<head> 这样的结构标签不支持 id 标签。
HTML id 属性示例
以下示例将说明 HTML id 属性,我们应该在何处以及如何使用此属性!
使用 id 属性进行文本操作
在此示例中,我们将创建一个文本内容并通过 JavaScript 操作文本,方法是通过定义的 id 选择元素。
<!Doctype html>
<html>
<body>
<h3>HTML id Attribute</h3>
<strong id="myId">QikepuCom</strong>
<p>
Click this
<button onclick="changeElement()">Button</button>
to see the change
</p>
<script>
function changeElement() {
document.getElementById("myId").innerHTML =
"Simply Easy Learning!";
}
</script>
</body>
</html>
使用 id 属性访问 div 元素
考虑到另一种情况,我们将使用 id 属性和 div 元素来使用 CSS 为其应用样式。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML id attribute</title>
<style>
/*access element using #id_name */
#demo {
width: 310px;
height: 120px;
background-color: green;
align-items: left;
border-radius: 10px;
}
#demo p {
color: white;
letter-spacing: 1px;
text-align: center;
}
</style>
</head>
<body>
<!-- Example of HTML 'id' attribute -->
<strong>HTML 'id' attribute</strong>
<div id="demo">
<p>
HTML id attribute is used to uniquely identify
an element within an HTML document, allowing
for targeted styling, scripting, and linking.
</p>
</div>
</body>
</html>
使用 id 作为选择器来设置表单样式
让我们看一下另一个示例,我们将在 CSS 的帮助下使用 id 属性和 form 元素来设置登录表单的样式。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML id attribute</title>
<style>
/*access element using #id_name */
#myForm {
width: 300px;
height: 210px;
background-color: aqua;
border-radius: 10px;
text-align: center;
}
#myForm h1 {
text-align: center;
font-family: sans-serif;
margin-top: 5px;
}
#myForm input {
padding: 8px;
margin: 5px 0px;
}
#myForm button {
width: 105px;
padding: 8px;
}
</style>
</head>
<body>
<!-- Example of HTML 'id' attribute -->
<p>Example of HTML 'id' attribute</p>
<form id='myForm'>
<h1>Login</h1>
<br> Username:
<input type="text">
<br> Password:
<input type="password">
<br>
<button>Login</button>
</form>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |