javascript - 通过className设置的背景色为什么不能用xxx.style.backgroundColor来输出?

查看:136
本文介绍了javascript - 通过className设置的背景色为什么不能用xxx.style.backgroundColor来输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #a{
            width: 100px;
            height: 100px;
            border:1px solid;
        }
        .color{
            background: red;
        }
    </style>
</head>
<body>
    <div id="a">

    </div>
</body>
<script type="text/javascript">
    var div = document.getElementById('a');
    div.className = 'color';
    document.write(div.style.backgroundColor);
</script>

输出为空

解决方案

style.backgroundColor得到是属于这个Element本身的样式,不包括因匹配class而获得的样式。你想要的那个可以用getComputedStyle

这篇关于javascript - 通过className设置的背景色为什么不能用xxx.style.backgroundColor来输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆