Javascript 当CSS属性background设置元素时,如何获取元素的backgroundColor?
设置元素背景色属性的一种方法是使用Javascript 当CSS属性background设置元素时,如何获取元素的backgroundColor?,javascript,html,css,frontend,Javascript,Html,Css,Frontend,设置元素背景色属性的一种方法是使用background:#someColorValue。但是,这样做不会更改该元素的样式中的backgroundColor属性。因此,当我使用element.style.backgroundColor时,它返回一个空字符串。 直接使用background color属性设置颜色时,不会出现此问题。为什么会发生这种情况???当您访问元素的样式()属性时,您正在访问其内联样式。这意味着,如果通过类为元素提供样式,则仍然无法通过style访问它。因此,它将返回一个空字符
background:#someColorValue
。但是,这样做不会更改该元素的样式
中的backgroundColor
属性。因此,当我使用element.style.backgroundColor
时,它返回一个空字符串。
直接使用
background color
属性设置颜色时,不会出现此问题。为什么会发生这种情况???当您访问元素的样式
()属性时,您正在访问其内联样式。这意味着,如果通过类为元素提供样式,则仍然无法通过style
访问它。因此,它将返回一个空字符串('
)
另一方面,返回:
。。。在应用活动样式表并解析这些值可能包含的任何基本计算之后,元素的所有CSS属性的值
这意味着您可以访问通过类提供的样式,因为它在应用所有活动样式表(包括通过类应用的样式表)之后提供所有CSS属性
在您的特定情况下,您正试图访问后台background
CSS属性实际上是一个属性,它还设置了许多其他与背景相关的CSS属性。当您使用background
仅指定颜色时,其他属性将自动插入其默认值。您可以通过ElementCSSInlineStyle.style
访问此background
属性。但是,当访问对象窗口中的背景时。getComputedStyle
返回时,您将始终得到一个空字符串。这是因为返回的对象没有键background
;它只有每个与背景相关的CSS属性的键(例如,背景颜色
,背景剪辑
,等等)
下面是一个简单的示例,演示如何无法通过元素的style
属性访问非内联样式,以及如何无法通过对象窗口访问速记属性的值。getComputedStyle
const-boxOne=document.querySelector(“#boxOne”)
const boxTwo=document.querySelector(“#boxTwo”)
log(`Box-One:background${boxOne.style['background']},background-color${boxOne.style['background-color']}`)
log(`Box Two:background${boxTwo.style['background']},background color${boxTwo.style['background-color']}`)
const boxOneComputedStyles=getComputedStyle(boxOne)
const boxTwoComputedStyles=getComputedStyle(boxTwo)
//getComputedStyle中没有“背景”键
log(`Box-One(计算样式):背景${boxOneComputedStyles['background']},背景色${boxOneComputedStyles['background-color']}`)
log(`Box-Two(计算样式):背景${boxTwoComputedStyles['background']},背景色${boxTwoComputedStyles['background-color']}')
#boxOne,
#第二箱{
背景:121212d;
边界半径:5px;
宽度:50px;
高度:50px;
边缘:1米;
}
尝试计算样式。您想使用javascript获取背景css属性的值吗?@Lain谢谢,它可以工作,但是这里发生了什么?您的意思是什么?@Lain我的意思是当我们使用计算样式方法时会发生什么?以及为什么在使用背景色时没有出现这个问题。