获取不到Dom的backgroundColor属性?


index.html


 <div id="box"></div>

index.css


 #box{
    width: 50px;
    height: 50px;
    background: red;
}

js:


 window.onload = function(){
    console.log(document.getElementById("box").style.backgroundColor);
}

最后输出为空。这里为什么获取不到DOM的style属性呢?

dom JavaScript

天道蓝蓝猫 8 years, 8 months ago

style 属性仅针对元素本身,不包含全局 CSS 样式

一直不高端 answered 8 years, 8 months ago

background: red=>background-color: red;

老夫石更啦 answered 8 years, 8 months ago

document.getElementById("box").style获取的是元素行间设置的样式,不能获取到css中设置的样式。如果要获取css中设置的样式,可以试试getComputedStyle(标准浏览器)或者currentStyle(ie低版本)

复活的翅膀 answered 8 years, 8 months ago

Your Answer