JavaScript | DOM 操作:CSS / クラス操作 – getComputedStyle

JavaScript
スポンサーリンク

getComputedStyle とは何か

getComputedStyle は、CSS の継承・外部スタイル・メディアクエリ・ユーザー設定などをすべて反映した「最終的な見え方」を取得するための関数です。element.style が返すのは“自分で直書きしたインライン値”だけですが、getComputedStyle はブラウザが描画に使っている確定値を返します。ここが重要です:見た目と一致する値が欲しいときは常に getComputedStyle を使い、インラインの確認だけなら element.style を使います。


基本の使い方(確定値を読む・単位は文字列)

<div id="box" class="card">内容</div>
<style>
  .card { width: 50%; padding: 16px; color: #333; }
</style>
<script>
  const box = document.getElementById("box");
  const cs = getComputedStyle(box);
  console.log(cs.width);         // 例: "400px"(最終的なピクセル値)
  console.log(cs.paddingLeft);   // "16px"
  console.log(cs.color);         // "rgb(51, 51, 51)" のような形式
</script>
HTML

getComputedStyle の各プロパティは「単位付きの文字列」で返ります。ここが重要です:計算に使うときは parseFloat で数値化し、CSS に再設定するときは文字列で単位を付けて渡します。


element.style との違い(インライン vs 最終形)

<div id="panel" style="width: 200px;"></div>
<style>
  #panel { width: 60%; }
</style>
<script>
  const panel = document.getElementById("panel");
  console.log(panel.style.width);            // "200px"(インラインだけ)
  console.log(getComputedStyle(panel).width); // 例: "480px"(実際のレイアウト結果)
</script>
HTML

element.style は“自分が直接書いた”値のみで、外部 CSS は見えません。getComputedStyle は“ブラウザが決めた”最終値です。ここが重要です:外部 CSS やメディアクエリを含めた表示の真実が欲しいなら、迷わず getComputedStyle。


箱モデルと box-sizing の影響(width の意味が変わる)

<div id="a" style="box-sizing:content-box; width:200px; padding:20px; border:4px solid;"></div>
<div id="b" style="box-sizing:border-box;  width:200px; padding:20px; border:4px solid;"></div>
<script>
  const ca = getComputedStyle(a);
  const cb = getComputedStyle(b);
  console.log(ca.width); // "200px"(コンテンツ幅)
  console.log(cb.width); // "200px"(見える箱幅)
</script>
HTML

box-sizing が content-box だと width は“中身の幅”、border-box だと“箱全体の幅”を指します。ここが重要です:数値の解釈は box-sizing 次第。プロジェクト全体で border-box を採用すると、見えるサイズと指定値が揃い、混乱が減ります。


実務で役立つ読み取り(継承色・行高・余白)

<p id="text" class="lead">文章</p>
<style>
  body { color: #222; }
  .lead { font-size: 18px; line-height: 1.6; margin-top: 12px; }
</style>
<script>
  const cs = getComputedStyle(document.getElementById("text"));
  const color = cs.color;                 // 継承された色が最終値で取れる
  const fontSize = parseFloat(cs.fontSize);    // 数値化して計算に使う
  const lineHeight = cs.lineHeight;            // "normal" なら計算式を別途用意
  const marginTop = parseFloat(cs.marginTop);  // 余白のピクセル値
</script>
HTML

line-height は “normal” が返ることがあり、正確なピクセル値が欲しいときは fontMetrics や実測で補います。ここが重要です:返り値の“形式”に注意し、必要なら数値化・補正のロジックを用意します。


擬似要素やメディアクエリの確認(状態を拾う)

<style>
  .btn::after { content: "→"; color: red; }
  @media (max-width: 600px) {
    .box { background: yellow; }
  }
</style>
<button id="btn" class="btn">保存</button>
<div id="box" class="box"></div>
<script>
  const after = getComputedStyle(document.getElementById("btn"), "::after");
  console.log(after.content); // 擬似要素の content を取得

  const bg = getComputedStyle(document.getElementById("box")).backgroundColor;
  console.log(bg); // 現在のメディアクエリが効いたかどうかを最終値で確認
</script>
HTML

第二引数に “::before” や “::after” を渡すと擬似要素のスタイルも読めます。ここが重要です:DOM に存在しない見た目(擬似要素)でも、getComputedStyle なら状態確認が可能です。


タイミングの注意(描画後に測る・非表示は測れない)

<div id="target" style="display:none; width:50%;"></div>
<script>
  window.addEventListener("load", () => {
    // display:none は幅・高さが 0 になり、計測が不正確
    const el = document.getElementById("target");
    const prev = el.style.display;
    el.style.display = "block";                    // 一時的に表示
    const width = getComputedStyle(el).width;      // 正しい最終値を取得
    el.style.display = prev;
    console.log(width);
  });
</script>
HTML

画像やフォントが未読み込みだと確定値が変わることがあります。ここが重要です:初回計測は load 後、または requestAnimationFrame でフレーム境界に合わせる。display:none の要素は一時表示してから測るのが安全です。


レイアウトと座標の併用(rect と組み合わせる)

<div id="tooltip" class="tip">ヒント</div>
<script>
  const tip = document.getElementById("tooltip");
  const cs = getComputedStyle(tip);
  const rect = tip.getBoundingClientRect();
  // 背景色や境界幅は cs から、画面上の位置・サイズは rect から取得
  console.log(cs.backgroundColor, parseFloat(cs.borderWidth), rect.left, rect.top);
</script>
HTML

サイズや位置が必要なら rect、見た目の最終値は getComputedStyle。ここが重要です:用途を分けて併用すると、UI の合わせ込みが正確になります。


パフォーマンスの勘所(読み取りと書き込みの順序)

getComputedStyle はレイアウト計算を発生させることがあります。直前に多数の style を変更してすぐ読み取ると、毎回再計算が走って重くなります。ここが重要です:先に“全部読む”→次に“全部書く”の順序を守り、連続更新は requestAnimationFrame に乗せてフレームごとにまとめると滑らかになります。


実践例:フェードイン演出の判定と同期

<div id="toast" class="toast">保存しました</div>
<style>
  .toast { opacity: 0; transition: opacity 200ms ease; }
  .toast.is-show { opacity: 1; }
</style>
<script>
  const toast = document.getElementById("toast");

  function showToast() {
    toast.classList.add("is-show");
    // 実際に 1 になったか最終値で確認してから副作用
    const cs = getComputedStyle(toast);
    if (parseFloat(cs.opacity) === 1) {
      setTimeout(() => toast.classList.remove("is-show"), 1500);
    }
  }
</script>
HTML

トランジション中の状態は class と getComputedStyle の“最終値”を使って同期させます。ここが重要です:視覚の状態を単一情報源(is-show)にしつつ、必要なら最終値で確認して副作用を安全に発火します。


まとめ

getComputedStyle は「ブラウザが描画に使う最終的なスタイル」を取得するための基本ツールです。element.style はインラインのみ、getComputedStyle は外部 CSS・継承・メディアクエリを含めた確定値を返す。返り値は単位付き文字列なので、数値化して計算し、再設定時は単位を付ける。箱モデルや box-sizing の違いを理解し、描画後に計測、display:none は一時表示で対処。座標は rect、見た目は computed——役割を分けて使いこなせば、初心者でも“見た目と同じ値”を正確に扱い、レイアウトや演出を意図通りに制御できます。

タイトルとURLをコピーしました