我有一个关于获取 X id 的问题 document.getElementById("X").style.backgroundColor 这是我的 HTML:
<div id ="X" class="main-sidebar text-white ">
</div>
CSS 类似:
.main-sidebar{
background-color: #343a40;
width:10%;
height:100%;
display:block;
position: absolute;
left:0px;
/*top:0px;*/
}
但是当我在 js 中使用 document.getElementById("X").style.backgroundColor 时,我得到 NULL 值...
最佳答案
这是因为 style
引用了 HTML 中的内联 style
属性。如果您想获取仅通过 CSS 设置的 style
,则需要使用 compulatedStyles
。
const elem = document.getElementsByTagName('p')[0]; // get element
const styles = window.getComputedStyle(elem); // get computed style of element
console.log(styles.getPropertyValue('background-color')); // get specific attribute
p {
background-color: red;
}
<p>Hi!</p>
关于javascript - 关于js获取背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54907335/