2012-01-04 114 views
2

我想:的Javascript,设置DIV颜色到另一个div的颜色

document.getElementById('colorsdiv').style.backgroundColor = 
    document.getElementById(thediv).style.backgroundColor; 

我知道thediv是有效的,因为如果我这样做: document.getElementById(thediv).style.backgroundColor = 'red';

则会变成红色。

如果我这样做: alert(document.getElementById(thediv).style.backgroundColor); 它是null

我也知道它在我的样式表中被设置为一种颜色,因为它以这种方式显示。

我需要做些什么才能使其发挥作用?

回答

4

要获得另一个元素的当前样式,使用此:

if(typeof getComputedStyle == "undefined") 
    getComputedStyle = function(elem) {return elem.currentStyle;}; 

document.getElementById('colorsdiv').style.backgroundColor 
    = getComputedStyle(document.getElementById(thediv)).backgroundColor; 
+0

如果我有一个样式表:#divname {background-color:black;}我将如何在JavaScript中引用它?如果我想要做一些像document.getElementById('colorsdiv')。style.backgroundColor = style('divname')。backgroundColor; – user999684 2012-01-04 01:20:18

+0

我使用了这个建议,它效果很好......谢谢 – user999684 2012-01-04 01:48:28

+0

请接受如果它为你工作的答案。 – 2012-01-04 01:59:39

0

你确保发现div的颜色JavaScript是后运行在页面完全加载,例如它在你html的body部分。这可以确保页面已加载并呈现颜色,以便脚本在运行时可以检索它。