JS获得元素颜色

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{background: RGB(222,222,2);}
</style>
</head>

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


<script type="text/javascript">
/*
*javascript的style属性只能获取内联样式,对于外部样式和嵌入式样式*需要用currentStyle属性。但这种方法有兼容性(FF和Chrome不支持)
*/
HTMLElement.prototype.__defineGetter__("currentStyle", function() {
return this.ownerDocument.defaultView.getComputedStyle(this, null);
});

function fun(){
var color = document.body.currentStyle.backgroundColor;
alert(color);
}
</script>
</body>

</html>

 

posted @ 2017-03-05 19:44  momo2525  阅读(3135)  评论(0编辑  收藏  举报