class id區別

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配置的屬性顯示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章