HTML - bgcolor 屬性



HTML bgcolor 屬性用於表示元素(如 body、table、tr、th、td 等)的背景顏色。

此屬性不再使用,建議使用 CSS 的 `background-color` 屬性。可以使用 JavaScript 與此屬性結合來更改表格或其他元素的背景顏色。

HTML ‘bgcolor’ 屬性在 HTML5 中不受支援。

語法

<tag bgcolor = "value"></tag>

其中,value 可以是任何顏色名稱、十六進位制程式碼或 RGB 顏色程式碼。

應用於

以下列出的元素允許使用 HTML bgcolor 屬性。

元素 描述
<body> HTML <body> 標籤用於定義任何 HTML 文件的主體內容,這些內容將在網頁上呈現。
<table> HTML <table> 標籤允許我們透過提供行和列的功能來以組織化的方式排列資料。
<tr> HTML <tr> 標籤用於定義表格的一行。
<th> HTML <th> 標籤用於定義表格的表頭行。
<td> HTML <td> 標籤用於定義表格行內的單元格。

HTML bgcolor 屬性示例

以下程式碼演示了 bgcolor 屬性的用法

使用 body 標籤的 bgcolor 屬性

執行以下程式碼時,它將生成一個輸出,其中包含在網頁上顯示的已應用背景顏色的文字。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML bgcolor attribute</title>
</head>
<body bgcolor="red">
   <h1>Example of HTML 'bgcolor' attribute</h1>
</body>
</html>

表格元素的背景顏色

考慮另一種情況,我們將建立一個表格併為其定義背景顏色。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML bgcolor attribute</title>
   <style>
      table {
         color: white;
      }
   </style>
</head>

<body bgcolor='yellow'>
   <h1>Example of HTML 'bgcolor' attribute</h1>
   <table bgcolor="green" border='1'>
      <tr>
         <th>S.No</th>
         <th>Name</th>
         <th>Email</th>
      </tr>
      <tr>
         <td>1.</td>
         <td>Abc</td>
         <td>abc123@gmail.com</td>
      </tr>
      <tr>
         <td>2.</td>
         <td>Xyz</td>
         <td>xyz23@gmail.com</td>
      </tr>
   </table>
</body>

</html>

表格行的背景顏色

讓我們來看下面的例子,我們將把 bgcolor 屬性與 tr 元素一起使用。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML bgcolor attribute</title>
</head>

<body bgcolor='aqua'>
   <h1>Example of HTML 'bgcolor' attribute</h1>
   <p>Fruits and prices: </p>
   <table bgcolor="white" border='1'>
      <tr bgcolor='aquamarine'>
         <th>S.No</th>
         <th>Name</th>
         <th>Price</th>
      </tr>
      <tr>
         <td>1.</td>
         <td>Apple</td>
         <td>100 R/Kg</td>
      </tr>
      <tr>
         <td>2.</td>
         <td>Orange</td>
         <td>90 R/Kg</td>
      </tr>
      <tr>
         <td>3.</td>
         <td>Grapes</td>
         <td>130 R/Kg</td>
      </tr>
   </table>
</body>

</html>

動態更改背景顏色

在這個程式中,我們將建立一個按鈕,新增 onclick 事件,當用戶單擊按鈕時更改背景顏色。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML bgcolor attribute</title>
</head>
<body bgcolor='aqua'>
   <h1>Example of HTML 'bgcolor' attribute</h1>
   <p>Click on the below button to change the background color.</p>
   <button onclick="Changed()">Changed</button>
   <script>
      function Changed() {
         var d = document.querySelector("body")
         d.bgColor = "yellow";
      }
   </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
bgcolor
html_attributes_reference.htm
廣告
© . All rights reserved.