[JavaScript] CSS(スタイルシート)取得する方法

1 min read
hiroweb developer

概要

CSS ファイルで要素に設定されたスタイルを JS で動的に読込を行いたい。

方法

まず以下のような CSS を定義したスタイルシートを読み込んだページを用意する。

.container {
  margin-top: 50px;
}

このページ内で以下のようなスクリプトを記述する。

var container = document.querySelector(".container");
var marginTop = getStyleSheetValue(container, "margin-top");

///

function getStyleSheetValue(element, property) {
  if (!element || !property) {
    return null;
  }

  var style = window.getComputedStyle(element);
  var value = style.getPropertyValue(property);

  return value;
}

上記の処理で 50px が取得できる。

作成したgetStyleSheetValue関数に「要素」と「プロパティ名」を渡すことで、その指定プロパティの値が取得できる。

window.getComputedStyle

var style = window.getComputedStyle(element,pseudoElt);
  • elementは、計算されたスタイルを取得するelement オブジェクトです。
  • pseudoEltは、マッチさせたい疑似要素を指定する文字列です。通常要素には空文字列を指定してください。
  • styleは、CSSStyleDeclaration オブジェクトです。

関連