index.html
<p id="box"></p>
index.css
#box{
width: 50px;
height: 50px;
background: red;
}
js:
window.onload = function(){
console.log(document.getElementById("box").style.backgroundColor);
}
最后输出为空。这里为什么获取不到DOM的style属性呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
document.getElementById("box").style获取的是元素行间设置的样式,不能获取到css中设置的样式。如果要获取css中设置的样式,可以试试getComputedStyle(标准浏览器)或者currentStyle(ie低版本)
background: red=>background-color: red;
style 属性仅针对元素本身,不包含全局 CSS 样式