[Javascript] 要素のCSS値を確実に取得するgetComputedStyle

2020年4月8日

Javascript テクノロジー プログラミング

eyecatch 真冬にアイスを食べて、真夏にホットコーヒーを飲んでいる、ユゲタです。 「css」とかけまして、 「現役モデル」と、ときます。 そのココロは・・・ スタイルがいいでしょう。

たまに取得したくなる要素のスタイル値

WEBサービスを作っている時に、任意の要素にどういうcssが適用されているのかを、確認したい場面がたまにあります。 例えば、要素を表示したり隠したりするようなケースでは、class属性に、hiddenやviewなどのkey値で対応したり、data属性に0,1のフラグで登録していればいいのに、直接styleに書き込んだり、cssファイルに任せっきりにしてしまっている場合、要素のcss値を取得したくなります。 他にも、cssを複数のページで使いまわしている時に、現在の親要素の"position"が"absolute"なのか"relative"なのか"fixed"なのか、ページごとに何かしらの切り替えを行っているような場合、今現在どのスタイルが適用されているかを判断したくなるような場合もあります。 こうした時に、htmlやjavascriptで直接書き込んである以下のようなケースであれば、簡単に取得できるのだが、 <!--htmlに直書き--> <div style="display:none;">TEST</div> <!--javascriptで書き込み--> <div id="hoge">HOGE</div> <script> document.getelementById("hoge").style.setProperty("display","none",""); </script> cssに書き込まれている状態の値は、なかなか取得しづらい。 <div class="test">TEST</div> # test.css .test{ display:none; } このようなcssファイルに書かれている値を取得する方法って、できないかな〜と探してみたところ、 ちゃんとした命令が用意されていました。

要素のcss値の取得方法

HTMLタグのそれぞれの要素に適用されているcss値を取得する方法をいくつか紹介します。

1. style

要素の属性に直書きされている値であれば、style値から簡単に取得できます。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div id="test" style="width:100px;height:100px;border:1px solid red;"></div> <script> var elm = document.getElementById("test"); console.log(elm.style); </script> </body> </html> このように要素のstyleを取得してみると・・・ cssText: "width: 100px; height: 100px; border: 1px solid red;" length: 19 parentRule: null cssFloat: "" 0: "width" 1: "height" 2: "border-top-width" 3: "border-right-width" 4: "border-bottom-width" 5: "border-left-width" 6: "border-top-style" 7: "border-right-style" 8: "border-bottom-style" 9: "border-left-style" 10: "border-top-color" 11: "border-right-color" 12: "border-bottom-color" 13: "border-left-color" 14: "border-image-source" 15: "border-image-slice" 16: "border-image-width" 17: "border-image-outset" 18: "border-image-repeat" alignContent: "" alignItems: "" alignSelf: "" alignmentBaseline: "" all: "" animation: "" animationDelay: "" animationDirection: "" animationDuration: "" animationFillMode: "" animationIterationCount: "" animationName: "" animationPlayState: "" animationTimingFunction: "" backdropFilter: "" backfaceVisibility: "" background: "" backgroundAttachment: "" backgroundBlendMode: "" backgroundClip: "" backgroundColor: "" backgroundImage: "" backgroundOrigin: "" backgroundPosition: "" backgroundPositionX: "" backgroundPositionY: "" backgroundRepeat: "" backgroundRepeatX: "" backgroundRepeatY: "" backgroundSize: "" baselineShift: "" blockSize: "" border: "1px solid red" borderBlockEnd: "" borderBlockEndColor: "" borderBlockEndStyle: "" borderBlockEndWidth: "" borderBlockStart: "" borderBlockStartColor: "" borderBlockStartStyle: "" borderBlockStartWidth: "" borderBottom: "1px solid red" borderBottomColor: "red" borderBottomLeftRadius: "" borderBottomRightRadius: "" borderBottomStyle: "solid" borderBottomWidth: "1px" borderCollapse: "" borderColor: "red" ... という風に、無駄な値も含めてstyle関連の情報が取得できます。

2. cssText

<script> var elm = document.getElementById("test"); console.log(elm.style.cssText); console.log(elm.getAttribute("style")); </script> > width: 100px; height: 100px; border: 1px solid red; > width:100px;height:100px;border:1px solid red; 書かれているとおりに取得したいのであれば、"getAttribute"で、解釈されたcssを取得したければ、"cssText"がいいでしょう。

3. getPropertyValue

cssの値というのは、書かれている一括テキストを取得するのではなく、propertyに対して何の値が入っているかを知りたいので、cssTextのような形で取得しても、自分で分解する関数を書いてさらに値を取得しなければいけないのですが、"getPropertyValue"を使えば、直に値を取得できます。 そんな時は以下のようにすると、値のみ取得することができます。 <script> var elm = document.getElementById("test"); console.log(elm.style.getPropertyValue("border")); </script> > 1px solid red

4. getComputedStyle

しかし、これまでの情報は、タグに直書きされていなければ、値を取得できないため、styleとして登録されている情報の取得にはならないので、そんな場合は、"getComputedStyle"を使って取得しなければいけません。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> #test{ background-color : blue; } </style> </head> <body> <div id="test" style="width:100px;height:100px;border:1px solid red;background-color:yellow;"></div> <script> var elm = document.getElementById("test"); console.log(elm.style.cssText); console.log(elm.getAttribute("style")); console.log(elm.style.getPropertyValue("background-color")); console.log(getComputedStyle(elm, null).getPropertyValue("background-color")); </script> </body> </html> 上記の全部入り状態のソースですが、これの返り値は以下のようになります。 > width: 100px; height: 100px; border: 1px solid red; background-color: yellow; > width:100px;height:100px;border:1px solid red;background-color:yellow; > yellow > rgb(255, 255, 0) cssに書かれた情報と、直書きされた情報がそれぞれ別に取得されていることが確認できるので、わかっていただけたかと思います。 cssでは"red"を指定したのに、返り値が"rgb(255, 255, 0)"となってしまっているのは、仕様として受け止めましょう。

ブラウザの対応状況

便利に使えそうな"getComputedStyle"命令ですが、ブラウザの対応状況はどんな感じでしょう。 いつものように、can i useサイトで調べてみました。 予想通りIE6-8が真っ赤になっていますが、現状サポート対象ブラウザの範囲では全く問題なさそうですね。 それにしても、IE8以下って、ブラウザとして、機能できてないので、使っている人認識した方がいいですよ・・・

人気の投稿

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。

ブログ アーカイブ