---
title: "我的理解：为什么obj.style.backgroundColor有时候取不到值？"
author: "clrw"
date: "2014-09-10T09:53:33Z"
tags: []
categories: ["Web前端"]
slug: "obj-style-backgroundcolor"
draft: false
lastmod: "2014-09-10T10:01:30Z"
id: 2114556
url: "https://clrw.iteye.com/blog/2114556"
---

obj.style.backgroundColor有时候能取到值，有时候取不到，这是为什么呢？看了下面的代码你就知道了。

```
<html>
    <head>
        <style type="text/css">
	    p {background-color: #ccc}
	</style>
	</head>
	<body>
	    <p id="demo" class="p">非内联样式。</p>
		<p id="demo2" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;">内联样式。</p>
	</body>
</html>

<script type="text/javascript">
    document.getElementById("demo").onclick = function() {
        alert(
            "高度："+this.style.height+"\n"+
            "宽度："+this.style.width+"\n"+
            "上边距："+this.style.marginTop+"\n"+
            "对齐："+this.style.textAlign+"\n"+
            "行高："+this.style.lineHeight+"\n"+
            "背景颜色："+this.style.backgroundColor
        );
        alert(
            "高度："+getRealStyle(this, "height")+"\n"+
            "宽度："+getRealStyle(this, "width")+"\n"+
            "上边距："+getRealStyle(this, "marginTop")+"\n"+
            "对齐："+getRealStyle(this, "textAlign")+"\n"+
            "行高："+getRealStyle(this, "lineHeight")+"\n"+
            "背景颜色："+getRealStyle(this, "backgroundColor")
        );
    };
    document.getElementById("demo2").onclick = function() {
        alert(
            "高度："+this.style.height+"\n"+
            "宽度："+this.style.width+"\n"+
            "上边距："+this.style.marginTop+"\n"+
            "对齐："+this.style.textAlign+"\n"+
            "行高："+this.style.lineHeight+"\n"+
            "背景颜色："+this.style.backgroundColor
        );
    };

    // 一定要取到值怎么办？可以用下面这个方法。
    function getRealStyle(obj, styleName) {
        var realStyle = null;
        if(obj.currentStyle) {
            realStyle = obj.currentStyle[styleName];
        } else if(window.getComputedStyle) {
            realStyle = window.getComputedStyle(obj, null)[styleName];
        }
        return realStyle;
    }
</script>
```

 我个人的理解和结论就是内联样式是可以取到值的，否则是取不到的，一定要取到值怎么办？可以用代码中的getRealStyle(obj, styleName)获取。