HTML 属性class
用于指定 HTML 元素的类。多个 HTML 元素可以共享同一个类。
使用类属性
class
属性通常被用于指向样式表中的类名。它也可以被JavaScript用来访问和使用特定类名的元素。
创建类很简单,写一个句点(.),后跟一个类名。 然后,在大括号{}中定义 CSS 属性。
在下面的例子中,我们有三个元素,它们具有属性值为 city
。所有三个元素将根据 head
中的样式平等地定义设置样式:<div>class<div>
.city
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
</body>
</html>
再举个例子 <div>class<div>
.note
<!DOCTYPE html>
<html>
<head>
<style>
.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1>My <span class="note">Important</span> Heading</h1>
<p>This is some <span class="note">important</span> text.</p>
</body>
</html>
class
属性可用于任何 HTML 元素。类名要区分大小写!
多个类
HTML 元素可以属于多个类。
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
.main {
text-align: center;
}
</style>
</head>
<body>
<h2>Multiple Classes</h2>
<p>Here, all three h2 elements belongs to the "city" class. In addition, London also belongs to the "main" class, which center-aligns the text.</p>
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
</body>
</html>
不同的元素可以共享同一个类
不同的 HTML 元素可以指向相同的类名。在下面的示例中,<h2>
和<p>
都指向“city”类并将共享相同的样式:
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
在 JavaScript 中使用 class
JavaScript 也可以使用该类名来执行某些任务特定元素。JavaScript 可以使用以下方法访问具有特定类名的元素:getElementsByClassName()
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>
点击按钮到回调函数 myFunction()
,如下图所示
网友评论