我的理解:为什么obj.style.backgroundColor有时候取不到值?

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)获取。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值