开发者

Copying the background color of an HTML element

开发者 https://www.devze.com 2023-02-12 23:27 出处:网络
I\'d like to set the background color of an HTML element to the backg开发者_StackOverflowround color of another HTML element. This needs to happen at runtime using Javascript. I tried the following bu

I'd like to set the background color of an HTML element to the backg开发者_StackOverflowround color of another HTML element. This needs to happen at runtime using Javascript. I tried the following but it fails silently (the background color remains unaltered):

DOM.setElementProperty(element, "backgroundColor", "document.getElementById('country').style.backgroundColor");

Any ideas?


This is untested, but I would try

element.getStyle().setBackgroundColor(DOM.getElementById("country").getStyle().getBackgroundColor());


If you happen to be using a JS framework (jQuery, MooTools, etc), it should be as simple as something like (all code untested):

$("div2").attr("background") = $("div1").attr("background")

I normally just run with a framework (because I'm already using it elsewhere), but basic JavaScript should also be pretty simple as well, something along the lines of:

getElementByID("div2").setAttribute('background') = getElementByID("div1").getAttribute('background')

or

getElementByID("div2").Attribute('background') = getElementByID("div1").Attribute('background')

One thing I noticed in a quick reference search, though, is that the basic JavaScript method isn't consistent across browsers (IE seems to be quirky). Just something to keep in mind on that front.

0

精彩评论

暂无评论...
验证码 换一张
取 消