js 如何获取背景色的值?

JavaScript011

js 如何获取背景色的值?,第1张

javascript的style属性只能获取内联样式,对于外部样式和嵌入式样式需要用currentStyle属性。但是,currentStyle在FIrefox和Chrome下不支持,需要使用如下兼容性代码

HTMLElement.prototype.__defineGetter__("currentStyle", function () { 

    return this.ownerDocument.defaultView.getComputedStyle(this, null) 

})

接下来就可以直接使用currentStyle属性来获取元素的样式了,下面实例演示获取页面body的背景色:

1、HTML结构

<input type='button' value='点击按钮获取页面背景色' onclick="fun()"/>

2、CSS样式

body{background: RGB(222,222,2)}

3、javascript代码

HTMLElement.prototype.__defineGetter__("currentStyle", function () { 

return this.ownerDocument.defaultView.getComputedStyle(this, null) 

})

function fun(){

var color = document.body.currentStyle.backgroundColor

alert(color)

}

4、效果演示

1、首先我们来创建一个p元素,在里面写上hello:。

2、在浏览器界面上的显示如下。

3、接下来我们就为这个p元素来设置背景颜色。

4、接下来看看浏览器中变化。

5、说明我们就已经为p元素改好了背景色,如果要改变颜色的话直接在后面改就好。