簡體   English   中英

Javascript,將div顏色設置為另一種divs顏色

[英]Javascript, set div color to another divs color

我試過了:

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

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

它變成紅色。

如果我這樣做: alert(document.getElementById(thediv).style.backgroundColor); 它為null

我也知道在樣式表中將其設置為一種顏色,因為它以這種方式顯示。

我需要做什么才能使它正常工作?

要獲取另一個元素的當前樣式,請使用以下命令:

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

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

您是否確定在頁面完全加載運行找到div顏色的javascript,例如它在html的body部分中。 這樣可以確保頁面已加載並呈現顏色,以便腳本可以在運行時檢索它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM