body.style.backgroundColor和window.getComputedStyle(body)之间的差异.getPropertyValue('background-color') [英] Difference between body.style.backgroundColor and window.getComputedStyle(body).getPropertyValue('background-color')

查看:212
本文介绍了body.style.backgroundColor和window.getComputedStyle(body)之间的差异.getPropertyValue('background-color')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得身体的背景颜色,我想知道之间有什么区别:

I am trying to get the background color of the body, and I am wondering what is the difference between:

body.style。 backgrounColor

window.getComputedStyle(body).getPropertyValue('background-color')

假设 var body = document.getElementsByTagName(body)[0]

Given that var body = document.getElementsByTagName("body")[0];

有没有其他方法我可以得到背景颜色?

Is there any other way I can get the background-color?

推荐答案

使用:

body.style.backgroundColor

设置 style 直接在元素上,或返回通过style属性或属性设置的相关样式属性的当前值。在应用 CSS规则(如果有的话)。

sets the style directly on an element, or returns the current value of the related style property that has been set through the style attribute or property. Such values are considered by a user agent when determining how to display an element when applying CSS rules (if there are any).

元素的样式对象不一定反映通过CSS规则应用于元素的值,虽然它们可能是相同的故意将两者设置为相同的值)。

An element's style object does not necessarily reflect values applied to an element through CSS rules, though they may be the same (by chance or deliberately setting both to the same value).

样式规则应用于元素的顺序列在 CSS2.1规范。在!important 声明之后,直接应用于元素的规则具有第二高的优先级。

The order in which style rules are applied to an element are listed in the CSS2.1 spec. Rules applied directly to the element are of second highest precedence, after !important declarations.

使用:

window.getComputedStyle(body).getPropertyValue('background-color')

DOM Level 2 规范。基本上,它返回用于显示基于CSS规则的元素的当前样式属性值,即实际应用于元素的内容。

is described in the DOM Level 2 specification. Basically, it returns the current style property values being used to display an element based on CSS rules, i.e. what is actually being applied to the element.

这通常不同于相关样式属性的值(除非由属性或属性设置,否则没有值)。

This often different to the value of the related style property (which not have a value unless set by a property or attribute).

这篇关于body.style.backgroundColor和window.getComputedStyle(body)之间的差异.getPropertyValue('background-color')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆