1. HTML class
class通常定义来为之后的显示方式:如下
其中intro类只能为h1使用,important可以为其他所有的类使用。
<html>
<head>
<style type="text/css">
h1.intro
{
color:blue;
text-align:center;
}
.important {background-color:yellow;}
</style>
</head>
<body>
<h1 class="intro important">Header 1</h1>
<p class="intro important">A paragraph.</p>
</body>
</html>
上例中p中字体颜色不会是蓝色和居中,因为intro 属性对p不起作用,而inportant对它起作用。
<head>
<style type="text/css">
h1.intro {color:blue;}
p {color:green;} 不要忘记还有此种定义方式
p.important {color:red;}
</style>
</head>
<body>
<h1 class="intro">Header 1</h1> 蓝色显示 Header
<p>A paragraph.</p> 绿色显示 A paragraph
<p class="important">请注意这个重要的段落。:)</p> 红色显示
</body>
2. HTML id
通过 JavaScript 利用 id 属性来改变一段文本:
<html>
<head>
<script type="text/javascript">
function change_header()
{
document.getElementByIdx_x("myHeader").innerHTML="Nice day!";
}
</script>
</head>
<body>
<h1 id="myHeader">Hello World!</h1>
<button οnclick="change_header()">Change text</button>
</body>
</html>
生成一段文字和一个按钮,点击该按钮,显示的文字将改变。
还有一种用法与class类似:
<html>
<head>
<style>
#myHeader
{
color:red;
text-align:center;
}
</style>
</head>
<body>
<h1 id="myHeader">W3School is the best!</h1>
</body>
</html>
相当于属性,显示的文字将根据head中id配置的属性显示。