class屬性設(shè)置類。 我們通常使用類來對(duì)元素進(jìn)行分組。
然后我們可以定位屬于給定類的元素并應(yīng)用CSS樣式。
<element class="classname">
![]() |
![]() |
![]() |
![]() |
![]() |
|
---|---|---|---|---|---|
class |
Yes | Yes | Yes | Yes | Yes |
<!DOCTYPE HTML> <html> <body> <a class="class1 class2" rel="external nofollow" target="_blank" >Apress web site</a> <p/> <a class="class2 otherclass" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" >W3C web site</a> </body> </html>
您可以通過使用空格分隔類名稱來對(duì)每個(gè)元素應(yīng)用多個(gè)類。
在下面的代碼中,我們創(chuàng)建了一個(gè)針對(duì)一個(gè)或多個(gè)類的樣式。
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.class2 {
background-color:grey; color:white; padding:5px; margin:2px;
}
.class1 {
font-size:x-large;
}
</style>
</head>
<body>
<a class="class1 class2" href="http://www.o2fo.com">web site</a>
<p/>
<a class="class2 otherclass" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" >W3C web site</a>
</body>
</html>
另一種使用類屬性的方法是在腳本中。
<!DOCTYPE HTML>
<html>
<body>
<a class="class1 class2" href="http://www.o2fo.com">web site</a>
<br/>
<a class="class2 otherclass" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" >W3C web site</a>
<script type="text/javascript">
var elems = document.getElementsByClassName("otherclass");
for (i = 0; i < elems.length; i++) {
var x = elems[i];
x.style.border = "thin solid black";
x.style.backgroundColor = "white";
x.style.color = "black";
}
</script>
</body>
</html>
上面的腳本查找所有的元素已分配給 otherclass
類并應(yīng)用一些樣式。
更多建議: