高校倫理1433840 views
LaTeX957673 views
中学英語809046 views
中学理科1626729 views
世界の国560930 views
英語608453 views
MathPython492025 views
高校国語785873 views
小学社会308762 views
りんご194232 views
Help
Tools

English

getComputedStyle で計算済みスタイルを取得する

getComputedStyle は、要素に実際に適用されているスタイルを取得する関数です。CSS ファイルで設定したスタイルも取得できます。

element.style との違い

element.style はインラインスタイルしか取得できません。CSS ファイルや <style> タグで設定したスタイルは取得できません。

<style>
  #box { color: red; font-size: 16px; }
</style>
<div id="box">テスト</div>
const box = document.getElementById('box');

// style では取得できない
console.log(box.style.color);     // ""(空)
console.log(box.style.fontSize);  // ""(空)

// getComputedStyle なら取得できる
const computed = getComputedStyle(box);
console.log(computed.color);      // "rgb(255, 0, 0)"
console.log(computed.fontSize);   // "16px"

基本的な使い方

const element = document.getElementById('target');
const styles = getComputedStyle(element);

// 各プロパティを取得
console.log(styles.width);
console.log(styles.height);
console.log(styles.backgroundColor);
console.log(styles.padding);

計算済みの値が返る

名前の通り「計算済み」の値が返ります。

// CSS で width: 50% と設定していても
console.log(styles.width); // "250px" のように計算後の値

// 色は rgb() 形式で返る
console.log(styles.color); // "rgb(255, 0, 0)"

実際に動かしてみよう

HTML
CSS
JavaScript
<div id="target">スタイルを確認</div>
<button id="checkBtn">スタイルを取得</button>
<pre id="result"></pre>
#target {
  width: 200px;
  padding: 20px;
  background-color: #4caf50;
  color: white;
  font-size: 18px;
  border-radius: 8px;
}
document.getElementById('checkBtn').addEventListener('click', () => {
  const target = document.getElementById('target');
  const styles = getComputedStyle(target);
  
  const info = [
    'width: ' + styles.width,
    'padding: ' + styles.padding,
    'backgroundColor: ' + styles.backgroundColor,
    'color: ' + styles.color,
    'fontSize: ' + styles.fontSize
  ];
  
  document.getElementById('result').textContent = info.join('\n');
});

疑似要素のスタイルを取得

第2引数で疑似要素を指定できます。

const styles = getComputedStyle(element, '::before');
console.log(styles.content);

getComputedStyle の注意点

読み取り専用

getComputedStyle で取得した値は変更できない。変更するには style プロパティを使う

パフォーマンス

呼び出すたびに計算が発生するので、ループ内で何度も呼ばないほうがよい

使いどころ

element.style

スタイルを設定するとき。インラインスタイルの取得

getComputedStyle

実際に適用されているスタイルを知りたいとき

// 現在の幅を取得して、それをもとに計算
const styles = getComputedStyle(element);
const currentWidth = parseInt(styles.width);
element.style.width = (currentWidth + 100) + 'px';

getComputedStyle は、現在のスタイルを知る必要があるときに使う強力なツールです。