Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

通过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>

输出为空


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...