2016-12-11 6 views
-1

要素のクラス名で設定された要素のCSSプロパティにアクセスすることはありませんか?javascriptを使用して要素の背景を取得する方法

最初のdiv要素については、私はバックグラウンドとして赤を設定した赤いクラスを付けました。また、javascriptでdivの背景色にアクセスしようとするとできません。 CSSクラスによって要素が要素style属性でbackground-color設定されていません

window.onload = function() { 
 
    var div = document.querySelector('.red'); 
 
    console.log(div.style.backgroundColor); 
 
    var div_2 = document.querySelector('div:nth-child(2)'); 
 
console.log(div_2.style.backgroundColor); 
 
}
.red { 
 
    background: red; 
 
} 
 
div:nth-child(2) { 
 
    background: green; 
 
}
<div class="red"> 
 
    Element1 
 
</div> 
 
<div id="div1"> 
 
    Element2 
 
</div>

おかげ

+1

これと同様の問題を見てみましょう:http://stackoverflow.com/questions/17588801/document-body-style-backgroundcolor-is-undefinedソリューションの – paulgv

答えて

1

を設定する際にJavaScriptを使用して、要素ののbackgroundColorにアクセスするための正しいアプローチはどのようなものです。 window.getComputedStyle()を使用して、.cssファイルに設定された要素計算スタイルを取得します。

window.onload = function() { 
 
    var div = document.querySelector('.red'); 
 
    console.log(window.getComputedStyle(div).backgroundColor); 
 
    var div_2 = document.querySelector('div:nth-child(2)'); 
 
    console.log(window.getComputedStyle(div_2).backgroundColor); 
 
}
.red { 
 
    background: red; 
 
} 
 
div:nth-child(2) { 
 
    background: green; 
 
}
<div class="red"> 
 
    Element1 
 
</div> 
 
<div id="div1"> 
 
    Element2 
 
</div>

+0

感謝を – Geeky

関連する問題