HTML - class 属性



HTML class 属性用于为 HTML 元素指定一个类,可以在单个元素上指定多个类。通过利用该 class 属性通过**CSS** 和**JavaScript** 选择元素,我们可以设置样式或更改该元素。

语法

<tag class="classname"></tag>

属性值

  • classname: classname 可以是您想要用来选择该元素的任何内容。

尝试点击图标 run button 运行按钮以运行以下 HTML 代码以查看输出。

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

HTML class 属性示例

使用 class 属性设置背景颜色

在此示例中,我们将使用 class 属性,并在 css 中使用该类名来选择该元素并将背景颜色设置为绿色并填充 5px。

Open Compiler
<!DOCTYPE html> <html> <head> <style> /* Class Selector Used to Select the Element */ .highlight { background-color: green; padding: 5px; } </style> </head> <body> <!-- HTML Class attribute used on p Element --> <p class="highlight">This is a highlighted paragraph.</p> </body> </html>

使用 class 属性设置悬停效果

在此示例中,我们将使用 class 属性,并在 CSS 中使用该类名来选择该元素并在选定元素上设置悬停效果。

Open Compiler
<!DOCTYPE html> <html> <head> <style> /* Class Selector Used to Select the Element */ .highlight:hover { background-color: green; padding: 5px; } </style> </head> <body> <!-- HTML Class attribute used on p Element --> <p class="highlight">This is a highlighted paragraph.</p> </body> </html>

使用 class 属性在 JavaScript 中设置背景颜色

在此示例中,我们将使用 class 属性,并在 JavaScript 中使用该类名来选择该元素并将背景颜色设置为绿色并填充 5px。

Open Compiler
<!DOCTYPE html> <html> <head> <script> /* Class Selector Used to Select the Element */ function myFunction() { let x = document.getElementsByClassName("highlight"); x[0].style.backgroundColor = "green"; x[0].style.padding = "5px"; } </script> </head> <body> <!-- HTML Class attribute used on p Element --> <p class="highlight">This is a highlighted paragraph.</p> <button onclick="myFunction()">Highlight</button> </body> </html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
class
广告