[英]Javascript, set div color to another divs color
I tried: 我试过了:
document.getElementById('colorsdiv').style.backgroundColor =
document.getElementById(thediv).style.backgroundColor;
I know thediv is valid, because if I do: document.getElementById(thediv).style.backgroundColor = 'red';
我知道thediv是有效的,因为如果我这样做:
document.getElementById(thediv).style.backgroundColor = 'red';
it turns red. 它变成红色。
If I do: alert(document.getElementById(thediv).style.backgroundColor);
如果我这样做:
alert(document.getElementById(thediv).style.backgroundColor);
it is null
. 它为
null
。
I also know that it is set to a color in my stylesheet because it displays that way. 我也知道在样式表中将其设置为一种颜色,因为它以这种方式显示。
What do I need to do to get this to work? 我需要做什么才能使它正常工作?
To get the current style of another element, use this: 要获取另一个元素的当前样式,请使用以下命令:
if( typeof getComputedStyle == "undefined")
getComputedStyle = function(elem) {return elem.currentStyle;};
document.getElementById('colorsdiv').style.backgroundColor
= getComputedStyle(document.getElementById(thediv)).backgroundColor;
Did you make sure the javascript that finds the div's color is run after the page has completely loaded, eg it is in your body section of the html. 您是否确定在页面完全加载后运行找到div颜色的javascript,例如它在html的body部分中。 This makes sure the page has loaded and rendered the color so the script can retrieve it when it is run.
这样可以确保页面已加载并呈现颜色,以便脚本可以在运行时检索它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.