HTML全局属性类

2018-01-05 13:58 更新

HTML全局属性类


class属性设置类。 我们通常使用类来对元素进行分组。

然后我们可以定位属于给定类的元素并应用CSS样式。

句法

<element class="classname">

属性值

classname
one or more class names for an element.

浏览器兼容性

class Yes Yes Yes Yes Yes


例子

<!DOCTYPE HTML>
<html>
    <body>
        <a class="class1  class2" href="http://apress.com" rel="external nofollow" target="_blank" >Apress web site</a>
        <p/>
        <a class="class2 otherclass" href="http://w3c.org" rel="external nofollow" target="_blank"  rel="external nofollow" target="_blank"  rel="external nofollow" target="_blank" >W3C web site</a>
    </body>
</html>



实施例2

您可以通过使用空格分隔类名称来对每个元素应用多个类。

在下面的代码中,我们创建了一个针对一个或多个类的样式。

<!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.w3cschool.cn">web site</a>
    <p/>
    <a class="class2 otherclass" href="http://w3c.org" rel="external nofollow" target="_blank"  rel="external nofollow" target="_blank"  rel="external nofollow" target="_blank" >W3C web site</a>
</body>
</html>

Click to view the demo

实施例3

另一种使用类属性的方法是在脚本中。

<!DOCTYPE HTML>
<html>
<body>
<a class="class1  class2" href="http://www.w3cschool.cn">web site</a>
<br/>
<a class="class2 otherclass" href="http://w3c.org" 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>

Click to view the demo

上面的脚本查找所有的元素已分配给 otherclass 类并应用一些样式。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号