如何用js自动获取图片的背景颜色,急急急...

JavaScript022

如何用js自动获取图片的背景颜色,急急急...,第1张

div 里面background设置属性background:url('图片地址') 0 0 no-repeat ;background-size:100% 100%就可以了上面background 的 0 0 是 x y 轴的偏移量 no-repeat是如果背景图片不重复出现

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、效果演示

//获取第一个a标签的背景色

var color = document.getElementsByTagName("a")[0].style.backgroundColor

//输出颜色

document.write(color)