Този сайт ще има ограничена функционалност, докато се извършва тече неговата поддръжка. Ако дадена статия не може реши проблема ви и искате да зададете въпрос, нашата общност е готова да ви помогне на @firefox в Twitter и /r/firefox в Reddit.

Търсене в помощните статии

Избягвайте измамите при поддръжката. Никога няма да ви помолим да се обадите или изпратите SMS на телефонен номер или да споделите лична информация. Моля, докладвайте подозрителна активност на "Докладване за злоупотреба".

Научете повече

Why a css attribute defined using a class in css is not acessible via style property in javascript?

more options

for example html

<div id="greendiv" class="green"></div>

 css
.green {
background-color: green;
}
javascript:
var divcolor = document.getElmentById("greendiv").style.backgroundColor;

Problem: divcolor does not get 'green', backgroundColor has no value;

the same is true for 'getAttribute()';

for example html <pre><nowiki><div id="greendiv" class="green"></div> css .green { background-color: green; }</nowiki></pre> javascript: <pre><nowiki>var divcolor = document.getElmentById("greendiv").style.backgroundColor; </nowiki></pre> Problem: divcolor does not get 'green', backgroundColor has no value; the same is true for 'getAttribute()';

Променено на от cor-el

Всички отговори (4)

more options

That only works if you define the background-color via a style attribute and not via a style sheet.

<div id="greendiv" style="background-color: green;"></div>
var divcolor = document.getElementById("greendiv").style.backgroundColor;

Otherwise you need to use getComputedStyle

N=document.getElementById("greendiv");
window.getComputedStyle(N,'').getPropertyValue("background-color");
document.defaultView.getComputedStyle(N,'').getPropertyValue("background-color");

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView

more options

That is annoying a simple change in design and the code is broken...

There ain't a way to reach the data no matter how I set up?

more options

The web is really disgusting all those silly and incompatible standards that just bloat up memory and cause no ease ...

more options

Hi alfgaar, this is very old behavior, and you're not the first person to find it clumsy/awkward to have to use getComputedStyle().

To give you an example, here's an article from April 2006 proposing an alternate function that can easily check both inline styles and other styles in one step:

https://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/

You may find it more convenient to use a JavaScript library for this, or grab some of their code for your use. For example, using jQuery:

http://api.jquery.com/css/