我有一个 javascript 函数,当用户单击一个 div 以获取网页的当前背景颜色(在我的笔记本电脑上为白色)时调用该函数:
<div id="div1" onclick="checkbkcolor(id, 1)">Just testing the web page bk color
</div>
这里是 checkbkcolor() 函数:
<head>
<script type="text/javascript">
// DOES NOTHING SO I COMMENTED IT OUT: document.body.style.backgroundColor = "red";
function checkbkcolor(id, val)
{
// THIS RETURNS NOTHING FOR THE COLOR -- the alert box
// only says "the document.body.style.backgroundColor is: "
// and nothing else
alert("the document.body.style.backgroundColor is: "
+ document.body.style.backgroundColor);
document.body.style.backgroundColor = "red";
// The alert box now shows 'red' for the color name, *AND*
// the web page's background has turned all red
alert("the document.body.style.backgroundColor is: "
+ document.body.style.backgroundColor);
}
</script>
</head>
换句话说:当页面出现时我的网页背景是白色的,但没有设置 document.body.style.backgroundColor。
那么我的网页是否设置为“透明”?
我不这么认为。为了测试,我添加了以下 CSS 背景色,当网页第一次出现时,整个背景都是黄色的:
body
{
background-color: rgb(255,255,0);
}
现在,当我的网页出现时,它不再是白色的(或透明的,无论如何)。 网页出现时是黄色的。
而且还在。以下代码显示未设置背景颜色:
function checkbkcolor(id, region)
{
// THIS RETURNS NOTHING FOR THE COLOR
alert("the document.body.style.backgroundColor is: "
+ document.body.style.backgroundColor);
// same code other as above
}
我的假设是我对“bgColor”、“background”、“backgroundColor”的研究(值(value) 4 小时)没有帮助。
最重要的是,当我将 CSS 中的“body”设置为 rgb(255,255,0) 时,我不明白整个网页背景是如何变成黄色的,但下面的警告框显示背景颜色未设置:
alert("the document.body.style.backgroundColor is: "
+ document.body.style.backgroundColor);
我需要知道,当页面第一次出现时,背景颜色是什么。 怎么办?
编辑:我使用的是最新版本的 Firefox,版本 22.0
最佳答案
你在 alert 中得到一个空值,因为你在读取值之前没有设置 body
的背景颜色。在第二个警报中,它会为您提供值,因为您已经设置了它。
document.body.style
表示 body
中的内联 样式,而不是样式表中给出的样式。如果需要获取当前值,需要使用window.getComputedStyle()
像这样:
bgColor = window.getComputedStyle(document.body, null).getPropertyValue('background-color');
请注意,您可以使用 getPropertyvalue()
访问带有 CSS 名称的样式属性,或 JS 样式的驼峰式命名:
var bodyStyle = window.getComputedStyle(document.body, null);
bgColor = bodyStyle.backgroundColor;
fgColor = bodyStyle.color;
...
关于javascript - document.body.style.backgroundColor 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588801/