CFH*_*der 2 html javascript css
我有一个javascript函数,当用户单击div以获取网页的当前背景颜色(我的笔记本电脑上为白色)时调用该函数:
<div id="div1" onclick="checkbkcolor(id, 1)">Just testing the web page bk color
</div>
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
换句话说:当页面出现时我的网页背景为白色但未设置document.body.style.backgroundColor.
我的网页设置为"透明"吗?
我不这么认为.为了测试,我添加了以下CSS背景颜色,当网页首次出现时,整个背景为黄色:
body
{
background-color: rgb(255,255,0);
}
Run Code Online (Sandbox Code Playgroud)
现在,当我的网页出现时,它不再是白色(或透明,无论如何).出现时,网页为黄色.
还是.以下代码显示未设置背景颜色:
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
}
Run Code Online (Sandbox Code Playgroud)
我的假设是我对'bgColor','背景','backgroundColor'的研究(价值4小时)没有帮助.
最重要的是,当我将CSS中的'body'设置为rgb(255,255,0)时,我不明白整个网页背景是如何变黄的,但是下面的警告框说明backgroundColor未设置:
alert("the document.body.style.backgroundColor is: "
+ document.body.style.backgroundColor);
Run Code Online (Sandbox Code Playgroud)
我需要知道,当页面首次出现时,背景颜色是什么.怎么样?
编辑:我使用的是最新版本的Firefox,版本22.0
Tee*_*emu 18
在alert中获得一个空值,因为body在读取值之前没有设置背景颜色.在第二个警报中,它为您提供了值,因为您已经设置了它.
document.body.style表示样式表中给出的内联样式,而body不是样式表中给出的样式.如果您需要获取当前值,则需要使用window.getComputedStyle()如下:
bgColor = window.getComputedStyle(document.body, null).getPropertyValue('background-color');
Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用getPropertyvalue()或使用JS样式的camelCase名称访问CSS名称的样式属性:
var bodyStyle = window.getComputedStyle(document.body, null);
bgColor = bodyStyle.backgroundColor;
fgColor = bodyStyle.color;
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13694 次 |
| 最近记录: |