获取不到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属性呢?

阅读 5.9k
3 个回答

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

background: red=>background-color: red;

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题