html中的类:
类别是为HTML元素指定一个或多个类别名称的属性。
class属性可以在任何HTML元素上使用。
CSS和JavaScript可以使用该类名来为具有指定类名的元素执行某些任务。
例:
.country {
background-color:black;
color:white;
padding:8px;
}
CHINA
China has the largest population
in the world.
INDIA
India has the second largest
population in the world.
UNITED STATES
United States has the third largest
population in the world.
输出:
说明:在以上示例中,CSS用类名“country”设置了所有元素的样式。
在JavaScript中使用class属性:JavaScript可以使用getElementsByClassName()方法访问具有指定类名称的元素。
例:
function myFunction() {
var x = document.getElementsByClassName("country");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
Click the button, and a JavaScript hides all
elements with the class name "country":
Hide elements
CHINA
China has the largest population in the world.
INDIA
India has the second largest population in the world.
UNITED STATES
United States has the third largest population
in the world.
输出:
在单击“隐藏元素”按钮之前:
单击“隐藏元素”按钮后:
使用多个类:
HTML元素可以具有多个类名,其中每个类名必须用空格分隔。
例:
.country {
background-color:black;
color:white;
padding:10px;
}
.middle {
text-align:center;
}
CHINA
INDIA
UNITED STATES
输出:
说明:所有三个头均具有类名“country”,但除此之外,CHINA也具有类名“middle”,这使得文本为center-aligned。
在不同的标记中使用相同的类:不同的标记(例如
和
)可以具有相同的类名,从而共享相同的样式。
例:
.country {
background-color:black;
color:white;
padding:10px;
}
CHINA
China has the largest
population in the world.
输出:
说明:即使两个元素没有相同的标签名,它们也可以具有相同的类名,并具有相同的样式。
支持的浏览器:下面列出了Class属性支持的浏览器:
谷歌浏览器
IE浏览器
Firefox
Opera
Safari