HTML - 全域性 id 屬性



HTML 的 id 是一個全域性屬性,用於在文件中唯一標識一個元素,允許 CSS 或 JavaScript 用於樣式或操作目的。

“id”屬性應在 HTML 文件中唯一,以確保正常的功能並遵守 Web 標準。id 的名稱在 CSS 中由 "#" 關鍵字引用,在 JavaScript 中由 document.getElementById("id_name") 等 Dom 方法引用。

語法

<element id = "id_name" >

id_name 可以是任何內容,但不要在其他元素上使用相同的 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>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
id
html_attributes_reference.htm
廣告