javascript - 关于js获取背景颜色

标签 javascript html

我有一个关于获取 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/

相关文章:

javascript - 如何清除 jQuery 中的输入字段?

html - 如何隐藏 Canvas 中照片的溢出?

javascript - KineticJS 在 Jsfiddle 中工作,而不是在我的网站上工作

javascript - 如何从样式化组件 (React) 访问 CSS 值?

javascript - 让我的 JS 响应式?

javascript - 在菜单中嵌入 YUI Treeview

javascript - 在追加列表项后刷新有序列表的顺序

javascript - CSS3 过渡 : Expand fixed footer or fixed header to maximum size without overlaying Header or footer

HTML a, a :hover working, 但 a:selected 不是

javascript - 如何使用 JavaScript 向图像添加属性?