HTML - id 属性



HTML 的 id 属性用于在 HTML 文档中唯一标识一个元素,允许进行目标样式设置、脚本编写和链接。

此属性常用于样式、管理事件和更改文档结构。为了创建交互式和动态网页,它使开发人员能够定位特定部分并为其提供专门的行为和外观。

语法

<tag id = ‘id_name’></tag>

其中 id_name 可以是您选择的任何变量名称。

应用于

Id 属性是一个全局属性,这意味着几乎所有 HTML 标签都支持它。但是,像 <html>、<head> 这样的结构标签不支持 id 标签。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

HTML id 属性示例

以下示例将说明 HTML id 属性,以及我们应该在哪里以及如何使用此属性!

使用 id 属性进行文本操作

在此示例中,我们将创建一个文本内容并通过 JavaScript 操作文本,方法是通过定义的 id 选择元素。

Open Compiler
<!Doctype html> <html> <body> <h3>HTML id Attribute</h3> <strong id="myId">Tutorialspoint</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 为其应用样式。

Open Compiler
<!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 作为选择器来设置表单样式

让我们看看另一个示例,我们将使用 id 属性与表单元素一起使用,以借助 CSS 设置登录表单的样式。

Open Compiler
<!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>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
id
html_attributes_reference.htm
广告