javascript - document.body.style.backgroundColor is undefined -
i have javascript function called when user clicks div current background color (white on laptop) of web page:
<div id="div1" onclick="checkbkcolor(id, 1)">just testing web page bk color </div>
here checkbkcolor() function:
<head> <script type="text/javascript"> // nothing commented out: document.body.style.backgroundcolor = "red"; function checkbkcolor(id, val) { // returns nothing color -- alert box // says "the document.body.style.backgroundcolor is: " // , nothing else alert("the document.body.style.backgroundcolor is: " + document.body.style.backgroundcolor); document.body.style.backgroundcolor = "red"; // alert box shows 'red' color name, *and* // web page's background has turned red alert("the document.body.style.backgroundcolor is: " + document.body.style.backgroundcolor); } </script> </head>
in other words: web page background white when page appears document.body.style.backgroundcolor not set.
so web page set 'transparent'?
i don't think so. test, added following css background color , when web page first appears, entire background yellow:
body { background-color: rgb(255,255,0); }
now when web page appears, no longer white (or transparent, whatever). web page yellow when appears.
and still. following code shows background color not set:
function checkbkcolor(id, region) { // returns nothing color alert("the document.body.style.backgroundcolor is: " + document.body.style.backgroundcolor); // same code other above }
my assumption research (4 hours worth) on 'bgcolor', 'background', 'backgroundcolor' not helpful.
most of don't understand how entire web page background can come yellow when set 'body' in css rgb(255,255,0) , yet following alert box says backgroundcolor not set:
alert("the document.body.style.backgroundcolor is: " + document.body.style.backgroundcolor);
i need know, when page first appears, background color is. how?
edit: i'm using latest version of firefox, version 22.0
you empty value in alert, because haven't set background color of body
before reading value. in second alert gives value, since you've set it.
document.body.style
represents inline styles in body
, not style given in stylesheet. if need current values, need use window.getcomputedstyle()
this:
bgcolor = window.getcomputedstyle(document.body, null).getpropertyvalue('background-color');
note can access style properties css names using getpropertyvalue()
, or js style camelcase names:
var bodystyle = window.getcomputedstyle(document.body, null); bgcolor = bodystyle.backgroundcolor; fgcolor = bodystyle.color; ...
Comments
Post a Comment