HTML class 属性用于给 HTML 元素一个类,可以在单个元素上指定多个类。通过利用该类属性通过 CSS 和 JavaScript 选择元素,我们可以设置该元素的样式或更改该元素。
语法
<tag class="classname"></tag>
属性值
- classname:classname可以是您希望用来选择该元素的任何内容。
HTML 类属性的示例
使用 class 属性设置背景颜色
在这个例子中,我们将使用类属性,并在 css 中使用该类名来选择该元素并将背景颜色设置为绿色并填充 5px。
<!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 中使用该类名来选择该元素并在所选元素上设置悬停效果。
<!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>
在 JavaScript 中使用 class 属性设置背景颜色
在此示例中,我们将使用 class 属性,并在 JavaScript 中使用该类名来选择该元素并将背景颜色设置为绿色并填充 5px。
<!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>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | Yes | Yes | Yes | Yes |