<STYLE TYPE="text/css">
<!--
a {text-decoration:none;color:blue}
.test {text-decoration:none;color:blue}
-->
</STYLE>
普通はこのようにスタイルの指定をまとめてヘッダ部に書いておきます。
これを(たぶん)1枚のスタイルシートと呼びます。<LINK REL="STYLESHEET" TYPE="text/css" HREF="dom.css">このように外部のファイルを参照して定義することもできます。
もう1つは次のように個々のHTML要素にインラインに書いておく方法です。
<SPAN STYLE="color:red">赤</SPAN>スタイルシートの書式は次のようです。
selector {attribute:value;...}
selector の書式は次のようです。
tagname.classname#idtagname と classname と id はどれかがあればよいです。
IE4: HTMLElement.style.attribute = value NN4: HTMLElement.attribute = value例えば次のようなHTML要素があるとします。
コードは次のようです。
<DIV ID=div1 STYLE="position:relative;top:10;font-weight:bold;color:blue"> 牛乳は白い </DIV>これをスクリプトで少し右に動かしましょう。
if(document.all)
div1.style.left = 50;
else if(document.layers)
document.div1.left = 50;
document.styleSheets(index)
index は0から始まる整数か、そのスタイルシートの ID です。
<INPUT TYPE="button" VALUE="押してね☆"
ONCLICK="alert(document.styleSheets.length)">
a {text-decoration:none;color:blue}
をスタイルルールと呼びます。これは次のように得られます。
stylesheet.rules(index)index は0から始まる整数か、要素の ID です。
with(document.styleSheets(1).rules(4)) {
alert(selectorText); //A
alert(readOnly); //false
alert(style.color); //blue
}
例えば、次のような要素があったとします。
コードは次のようです。
<DIV CLASS=TEST ID=GUAM>女王様の指名</DIV>このクラスのスタイルは次のように定義されています。
.test {text-decoration:none;color:blue}
この色を変えるには2つの方法があります。
document.styleSheets(1).rules(1).style.color = 'red';
ルールを追加する方法もあります。
document.styleSheets(1).addRule('#guam', 'color:green');
addRule メソッドは次のように使います。
stylesheet.addRule(selector, style [, index])
style は例のようにスタイルシートを定義するのと同じように書きます。
index はルールを追加する位置を表す整数で、
0 だと最初、デフォルトは最後に追加します。
document.styleSheets(1).addRule('.test', 'text-decoration:underline', 1);
document.styleSheets(index)
index は0から始まる整数か、そのスタイルシートの ID です。
<INPUT TYPE="button" VALUE="押してね☆"
ONCLICK="alert(document.styleSheets.length)">
document.styleSheets(index).href = cssfilename