スタイル宣言について(CSSStyleDeclaration)
スタイル宣言について
■スタイル宣言について
スタイル宣言は、スタイルシートの宣言ブロックの1つ分に相当します。
宣言ブロックは、"{" から "}" までの間です。
CSSStyleDeclaration は、宣言ブロック1つ分に相当する
.test1 {
color: #f22;
background: #fcc;
width: 400px;
height: 300px;
}
.test2 {
font-size: 14px;
line-height: 1.4em;
}
■CSSStyleDeclaration インターフェースについて
スタイルを管理するための機能がまとまっています。
このページでは、CSSStyleDeclaration インターフェースで供給される機能について解説しています。
■エレメントのインラインスタイルについて
エレメントは、スタイル属性(インラインスタイル)を保有しています。
スタイル属性を使用すると、エレメントごとに、個別にスタイルを設定することができます。
エレメントのスタイル属性
<div style="color: #f22; background-color: #fcc; width: 400px; height: 300px;">
あいうえお
</div>
■エレメントから CSSStyleDeclaration オブジェクトを取得する
エレメントから、CSSStyleDeclaration オブジェクトを取得するには、style プロパティを使用します。
このオブジェクトは、スタイル属性に相当します。
エレメントから、CSSStyleDeclaration オブジェクトを取得する
<html>
<body>
<div id="aaa" style="color: #f22; background-color: #fcc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// "aaa" という ID 属性のエレメントを取得する
var element = document.getElementById("aaa");
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// 出力テスト
console.log(style);
//-->
</script>
</body>
</html>
■スタイルシート内のスタイル宣言について
スタイルシートが保有している、スタイル宣言にアクセスする事ができます。
スタイルシートについては、こちらで解説しています。
ドキュメント内のすべてのスタイルシートから、スタイル宣言を取得する
<html>
<head>
<style type="text/css">
<!--
#aaa { color: #822; font-size: 32px; }
-->
</style>
<style type="text/css">
<!--
.bbb { border: 10px #4c4 solid; }
[name="ccc"] { width:400px; height:300px; }
-->
</style>
</head>
<body>
<script type="text/javascript">
<!--
// --------------------------------------------------------------------------------
// スタイルシートから CSSRuleList オブジェクトを取得する関数
// --------------------------------------------------------------------------------
function CSSStyleSheetGetCSSRuleList(style_sheet){
try{
if(style_sheet.cssRules !== undefined){
return style_sheet.cssRules;
}else if(style_sheet.rules !== undefined){
return style_sheet.rules;
}
}catch(e){
}
return null;
}
// ------------------------------------------------------------
// スタイルシートを取得する
// ------------------------------------------------------------
// CSSStyleSheetList オブジェクトを取得する
var sheet_list = document.styleSheets;
// スタイルシートの総数を取得
var style_sheet_num = sheet_list.length;
var i;
for(i=0;i < style_sheet_num;i++){
// CSSStyleSheet オブジェクトを取得する
var style_sheet = sheet_list[i];
// ------------------------------------------------------------
// スタイルルールを取得する
// ------------------------------------------------------------
var rule_list = CSSStyleSheetGetCSSRuleList(style_sheet);
if(rule_list){
// スタイルルールの総数を取得
var rule_num = rule_list.length;
var j;
for(j=0;j < rule_num;j++){
// CSSStyleRule オブジェクトを取得する
var style_rule = rule_list[j];
// CSSStyleDeclaration オブジェクトを取得
var style = style_rule.style;
// 出力テスト
console.log(style);
}
}
}
//-->
</script>
</body>
</html>
■CSS2Properties インターフェースについて
プロパティを使って、スタイルにアクセスする事ができます。
CSSStyleDeclaration であれば、CSS2Properties インターフェースが実装されています。
■プロパティ名の規則について
「CSS プロパティ名」を、そのまま「プロパティ名」として使うことはできません。
以下のような規則があるようです。
『ハイフン "-"』の次の1字は、大文字となります。それ以外はすべて小文字となります。
『ハイフン "-"』を省略します。
■CSS2Properties のプロパティ名の一覧(一部抜粋)
| CSS プロパティ | プロパティ名 |
| azimuth | azimuth |
| background | background |
| background-attachment | backgroundAttachment |
| background-color | backgroundColor |
| background-image | backgroundImage |
| background-position | backgroundPosition |
| background-repeat | backgroundRepeat |
| border | border |
| border-collapse | borderCollapse |
| border-color | borderColor |
| border-spacing | borderSpacing |
| border-style | borderStyle |
| border-top | borderTop |
| border-right | borderRight |
| border-bottom | borderBottom |
| border-left | borderLeft |
| border-top-color | borderTopColor |
| border-right-color | borderRightColor |
| border-bottom-color | borderBottomColor |
| border-left-color | borderLeftColor |
| border-top-style | borderTopStyle |
| border-right-style | borderRightStyle |
| border-bottom-style | borderBottomStyle |
| border-left-style | borderLeftStyle |
| border-top-width | borderTopWidth |
| border-right-width | borderRightWidth |
| border-bottom-width | borderBottomWidth |
| border-left-width | borderLeftWidth |
| border-width | borderWidth |
| bottom | bottom |
| caption-side | captionSide |
| clear | clear |
| clip | clip |
| color | color |
| content | content |
| counter-increment | counterIncrement |
| counter-reset | counterReset |
| cue | cue |
| cue-after | cueAfter |
| cue-before | cueBefore |
| cursor | cursor |
| direction | direction |
| display | display |
| elevation | elevation |
| empty-cells | emptyCells |
| float | cssFloat (標準仕様) float (非標準、IE8以前専用) |
| font | font |
| font-family | fontFamily |
| font-size | fontSize |
| font-size-adjust | fontSizeAdjust |
| font-stretch | fontStretch |
| font-style | fontStyle |
| font-variant | fontVariant |
| font-weight | fontWeight |
| height | height |
| left | left |
| letter-spacing | letterSpacing |
| line-height | lineHeight |
| list-style | listStyle |
| list-style-image | listStyleImage |
| list-style-position | listStylePosition |
| list-style-type | listStyleType |
| margin | margin |
| margin-top | marginTop |
| margin-right | marginRight |
| margin-bottom | marginBottom |
| margin-left | marginLeft |
| marker-offset | markerOffset |
| marks | marks |
| max-height | maxHeight |
| max-width | maxWidth |
| min-height | minHeight |
| min-width | minWidth |
| orphans | orphans |
| outline | outline |
| outline-color | outlineColor |
| outline-style | outlineStyle |
| outline-width | outlineWidth |
| overflow | overflow |
| padding | padding |
| padding-top | paddingTop |
| padding-right | paddingRight |
| padding-bottom | paddingBottom |
| padding-left | paddingLeft |
| page | page |
| page-break-after | pageBreakAfter |
| page-break-before | pageBreakBefore |
| page-break-inside | pageBreakInside |
| pause | pause |
| pause-after | pauseAfter |
| pause-before | pauseBefore |
| pitch | pitch |
| pitch-range | pitchRange |
| play-during | playDuring |
| position | position |
| quotes | quotes |
| richness | richness |
| right | right |
| size | size |
| speak | speak |
| speak-header | speakHeader |
| speak-numeral | speakNumeral |
| speak-punctuation | speakPunctuation |
| speech-rate | speechRate |
| stress | stress |
| table-layout | tableLayout |
| text-align | textAlign |
| text-decoration | textDecoration |
| text-indent | textIndent |
| text-shadow | textShadow |
| text-transform | textTransform |
| top | top |
| unicode-bidi | unicodeBidi |
| vertical-align | verticalAlign |
| visibility | visibility |
| voice-family | voiceFamily |
| volume | volume |
| white-space | whiteSpace |
| widows | widows |
| width | width |
| word-spacing | wordSpacing |
| z-index | zIndex |
■アクセス例
プロパティを使って、スタイルにアクセスする
<html>
<body>
<div id="aaa" style="color: #f22; font-size :14px; border: 10px #c44 solid; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// ------------------------------------------------------------
// "aaa" という ID 属性のエレメントを取得する
// ------------------------------------------------------------
var element = document.getElementById("aaa");
// ------------------------------------------------------------
// CSSStyleDeclaration オブジェクトを取得
// ------------------------------------------------------------
var style = element.style;
// ------------------------------------------------------------
// スタイルを設定する
// ------------------------------------------------------------
style.borderColor = "#44c";
style.backgroundColor = "#ccf";
style.margin = "20px";
// ------------------------------------------------------------
// 出力テスト
// ------------------------------------------------------------
console.log(style.color);
console.log(style.fontSize);
console.log(style.borderTop);
console.log(style.borderBottomColor);
console.log(style.borderLeftWidth);
console.log(style.borderRightStyle);
console.log(style.backgroundColor);
console.log(style.width);
console.log(style.height);
//-->
</script>
</body>
</html>
スタイルを追加する
■プロパティを使ってスタイルを追加する
プロパティを使って、スタイルを追加することができます。
プロパティ名の規則については、こちらで解説しています。
プロパティを使って、エレメントにスタイルを設定する
// エレメントを作成する
var element = document.createElement("div");
// BODY のノードリストに登録する
document.body.appendChild(element);
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// スタイルを設定する
style.color = "#282";
style.fontSize = "32px";
style.border = "10px #4c4 solid";
style.backgroundColor = "#cfc";
style.width = "400px";
style.height = "300px";
■配列アクセス演算子を使ってスタイルを追加する
この方法は、非標準です。
CSS プロパティ名を使って、スタイルを追加することができます。
Internet Explorer 6 以前では、動作しません。
Firefox 34 以前では動作しません。
Opera(Presto 版) では、動作しません。
配列アクセス演算子を使って、エレメントにスタイルを設定する
// エレメントを作成する
var element = document.createElement("div");
// BODY のノードリストに登録する
document.body.appendChild(element);
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// スタイルを設定する
style["color"] = "#282";
style["font-size"] = "32px";
style["border"] = "10px #4c4 solid";
style["background-color"] = "#cfc";
style["width"] = "400px";
style["height"] = "300px";
■メソッドを使ってスタイルを追加する
スタイルを追加するには、setProperty() メソッドを使用します。
CSSStyleDeclaration.setProperty( "CSSプロパティ名" , "値" , "優先度名" ) :Void
| 第01引数 | String | CSS プロパティ名を指定する |
| 第02引数 | String | 値を指定する |
| 第03引数(略可) | String | 優先度名を指定する。例えば "important"。 |
| 戻り値 | Void | なし |
■ InternetExplorer 8 以前の場合
setProperty() メソッドは、InternetExplorer 8 以前では未対応です。
かわりに、プロパティからアクセスします。
スタイルを追加する関数
// --------------------------------------------------------------------------------
// スタイルを追加する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationSetProperty(style,property_name,value){
if(style.setProperty !== undefined){
style.setProperty(property_name,value);
}else{
style[property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); })] = value;
}
}
■設定例
メソッドを使って、エレメントにスタイルを設定する
// --------------------------------------------------------------------------------
// スタイルを追加する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationSetProperty(style,property_name,value){
if(style.setProperty !== undefined){
style.setProperty(property_name,value);
}else{
style[property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); })] = value;
}
}
// --------------------------------------------------------------------------------
// エレメントを作成
// --------------------------------------------------------------------------------
// エレメントを作成する
var element = document.createElement("div");
// BODY のノードリストに登録する
document.body.appendChild(element);
// --------------------------------------------------------------------------------
// CSSStyleDeclaration オブジェクトを取得
// --------------------------------------------------------------------------------
var style = element.style;
// --------------------------------------------------------------------------------
// スタイルを設定する
// --------------------------------------------------------------------------------
CSSStyleDeclarationSetProperty(style,"color", "#282");
CSSStyleDeclarationSetProperty(style,"font-size", "32px");
CSSStyleDeclarationSetProperty(style,"border", "10px #4c4 solid");
CSSStyleDeclarationSetProperty(style,"background-color", "#cfc");
CSSStyleDeclarationSetProperty(style,"width", "400px");
CSSStyleDeclarationSetProperty(style,"height", "300px");
スタイルを取得する
■プロパティを使ってスタイルの値を取得する
プロパティを使って、スタイルの値を取得することができます。
プロパティ名の規則については、こちらで解説しています。
エレメントのスタイルの値を取得する
<html>
<body>
<div id="aaa" style="color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// "aaa" という ID 属性のエレメントを取得する
var element = document.getElementById("aaa");
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// 出力テスト
console.log(style.color);
console.log(style.fontSize);
console.log(style.border);
console.log(style.backgroundColor);
console.log(style.width);
console.log(style.height);
//-->
</script>
</body>
</html>
■配列アクセス演算子を使ってスタイルの値を取得する
この方法は、非標準です。
CSS プロパティ名を使って、スタイルの値を取得することができます。
Internet Explorer 6 以前では、動作しません。
Firefox 34 以前では動作しません。
Opera(Presto 版) では、動作しません。
配列アクセス演算子を使って、エレメントのスタイルの値を取得する
<html>
<body>
<div id="aaa" style="color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// "aaa" という ID 属性のエレメントを取得する
var element = document.getElementById("aaa");
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// 出力テスト
console.log(style["color"]);
console.log(style["font-size"]);
console.log(style["border"]);
console.log(style["background-color"]);
console.log(style["width"]);
console.log(style["height"]);
//-->
</script>
</body>
</html>
■メソッドを使ってスタイルの値を取得する
スタイルの値を取得するには、getPropertyValue() メソッドを使用します。
CSSStyleDeclaration.getPropertyValue( "CSSプロパティ名" ) :String
| 第01引数 | String | CSS プロパティ名を指定する |
| 戻り値 | String | スタイルの値が得られる。CSS プロパティが存在しない場合は null が得られる。 |
■ InternetExplorer 8 以前の場合
getPropertyValue() メソッドは、InternetExplorer 8 以前では未対応です。
かわりに、プロパティからアクセスします。
スタイルの値を取得する関数
// --------------------------------------------------------------------------------
// スタイルの値を取得する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationGetPropertyValue(style,property_name){
if(style.getPropertyValue !== undefined){
return style.getPropertyValue(property_name);
}
return style[property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); })];
}
■取得例
エレメントのスタイルの値を取得する
<html>
<body>
<div id="aaa" style="color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// --------------------------------------------------------------------------------
// スタイルの値を取得する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationGetPropertyValue(style,property_name){
if(style.getPropertyValue !== undefined){
return style.getPropertyValue(property_name);
}
return style[property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); })];
}
// --------------------------------------------------------------------------------
// "aaa" という ID 属性のエレメントを取得する
// --------------------------------------------------------------------------------
var element = document.getElementById("aaa");
// --------------------------------------------------------------------------------
// CSSStyleDeclaration オブジェクトを取得
// --------------------------------------------------------------------------------
var style = element.style;
// --------------------------------------------------------------------------------
// 出力テスト
// --------------------------------------------------------------------------------
console.log(CSSStyleDeclarationGetPropertyValue(style,"color"));
console.log(CSSStyleDeclarationGetPropertyValue(style,"font-size"));
console.log(CSSStyleDeclarationGetPropertyValue(style,"border"));
console.log(CSSStyleDeclarationGetPropertyValue(style,"background-color"));
console.log(CSSStyleDeclarationGetPropertyValue(style,"width"));
console.log(CSSStyleDeclarationGetPropertyValue(style,"height"));
//-->
</script>
</body>
</html>
■スタイルの優先度を取得する
スタイルの優先度名を取得するには、getPropertyPriority() メソッドを使用します。
このメソッドは、InternetExplorer 8 以前では未対応です。
CSSStyleDeclaration.getPropertyPriority( "CSSプロパティ名" ) :String
| 第01引数 | String | CSS プロパティ名を指定する |
| 戻り値 | String | スタイルの優先度名が得られる。CSS プロパティが存在しない場合は null が得られる。 |
■すべてのスタイルを順番に取得する
InternetExplorer 8 以前では未対応です。
CSSStyleDeclaration オブジェクトは、配列のように中身を取り出せます。
中身は、登録済みである、CSS プロパティ名が格納されています。
スタイルの総数を取得するには、length プロパティを使用します。
エレメントのスタイルをすべて取得する
<html>
<body>
<div id="aaa" style="color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// ------------------------------------------------------------
// "aaa" という ID 属性のエレメントを取得する
// ------------------------------------------------------------
var element = document.getElementById("aaa");
// ------------------------------------------------------------
// CSSStyleDeclaration オブジェクトを取得
// ------------------------------------------------------------
var style = element.style;
// ------------------------------------------------------------
// 登録されているスタイルをすべて取得する
// ------------------------------------------------------------
var i;
// 登録されているスタイルの総数を取得
var num = style.length;
for(i=0;i < num;i++){
// CSS プロパティ名を取得
var property_name = style[i];
// 値を取得
var value = style.getPropertyValue(property_name);
// 優先度名を取得
var prio = style.getPropertyPriority(property_name);
// 出力テスト
console.log("id:" + i + " name:" + property_name + " value:" + value + " prio:" + prio);
}
//-->
</script>
</body>
</html>
■すべてのスタイルを CSS 文字列として取得する
すべてのスタイルを、1つの CSS 文字列として取得するには、cssText プロパティを使用します。
CSS 文字列を取得する
// エレメントを作成する
var element = document.createElement("div");
// BODY のノードリストに登録する
document.body.appendChild(element);
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// スタイルを設定する
style.color = "#282";
style.fontSize = "32px";
style.border = "10px #4c4 solid";
style.backgroundColor = "#cfc";
style.width = "400px";
style.height = "300px";
// CSS 文字列を取得する
console.log(style.cssText);
スタイルを除去する
■スタイルを除去する
スタイルを除去するには、removeProperty()メソッドを使用します。
CSSStyleDeclaration.removeProperty( "CSSプロパティ名" ) :String
| 第01引数 | String | 除去したい CSS プロパティ名を指定する |
| 戻り値 | String | 除去したスタイルの値が得られる。CSS プロパティが存在しない場合は null が得られる。 |
■ InternetExplorer 8 以前の場合
removeProperty() メソッドは、InternetExplorer 8 以前では未対応です。
かわりに、removeAttribute() メソッドを使用します。
CSSStyleDeclaration.removeAttribute( "CSSプロパティ名" , 大文字小文字を区別するか? ) :Boolean
| 第01引数 | String | 除去したい CSS プロパティ名を指定する。IE6 では、プロパティ名の表記にする必要がある。 "margin" のように、まとめてプロパティ名を指定する事はできない。この場合、"marginTop" , "marginBottom" , "marginLeft" , "marginRight" と分けて指定する。 |
| 第02引数(略可) | Boolean | 大文字小文字を区別したい場合 true を指定。デフォルトは true。 |
| 戻り値 | Boolean | 成功した場合 true。失敗した場合 false が得られる。 |
スタイルを除去する関数
// --------------------------------------------------------------------------------
// スタイルを除去する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationRemoveProperty(style,property_name){
if(style.removeProperty !== undefined){
style.removeProperty(property_name);
}else if(style.removeAttribute !== undefined){
property_name = property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); });
if(!style.removeAttribute(property_name,false)){
var re = new RegExp("^" + property_name + "[A-Z]");
var key;
for(key in style){
if(key.match(re)){
style.removeAttribute(key,false);
}
}
}
}
}
■使用例
エレメントのスタイルを除去する
<html>
<body>
<div id="aaa" style="color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;"></div>
<script type="text/javascript">
<!--
// --------------------------------------------------------------------------------
// スタイルを除去する関数
// --------------------------------------------------------------------------------
function CSSStyleDeclarationRemoveProperty(style,property_name){
if(style.removeProperty !== undefined){
style.removeProperty(property_name);
}else if(style.removeAttribute !== undefined){
property_name = property_name.replace(/([a-z]+)-([a-z])/g , function (str,p1,p2){ return p1 + p2.toUpperCase(); });
if(!style.removeAttribute(property_name,false)){
var re = new RegExp("^" + property_name + "[A-Z]");
var key;
for(key in style){
if(key.match(re)){
style.removeAttribute(key,false);
}
}
}
}
}
// --------------------------------------------------------------------------------
// "aaa" という ID 属性のエレメントを取得する
// --------------------------------------------------------------------------------
var element = document.getElementById("aaa");
// --------------------------------------------------------------------------------
// CSSStyleDeclaration オブジェクトを取得
// --------------------------------------------------------------------------------
var style = element.style;
// --------------------------------------------------------------------------------
// スタイルを除去する
// --------------------------------------------------------------------------------
CSSStyleDeclarationRemoveProperty(style,"color");
CSSStyleDeclarationRemoveProperty(style,"font-size");
CSSStyleDeclarationRemoveProperty(style,"border");
CSSStyleDeclarationRemoveProperty(style,"background-color");
CSSStyleDeclarationRemoveProperty(style,"width");
CSSStyleDeclarationRemoveProperty(style,"height");
//-->
</script>
</body>
</html>
CSS 文字列を使ってスタイルを構築する
■CSS 文字列を使ってスタイルを構築する
CSS 文字列を使ってスタイルを構築するには、cssText プロパティを使用します。
このプロパティに書き込みを行うと、登録済みのスタイルはすべてクリアされます。
CSS 文字列を使ってスタイルを構築する
// エレメントを作成する
var element = document.createElement("div");
// BODY のノードリストに登録する
document.body.appendChild(element);
// CSSStyleDeclaration オブジェクトを取得
var style = element.style;
// CSS 文字列を使ってスタイルを構築する
style.cssText = "color: #282; font-size: 32px; border: 10px #4c4 solid; background-color: #cfc; width: 400px; height: 300px;";