2012-01-04 106 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部分。這可以確保頁面已加載並呈現顏色,以便腳本在運行時可以檢索它。