Difference between body.style.backgroundColor and window.getComputedStyle(body).getPropertyValue('background-color')

后端 未结 4 1284
青春惊慌失措
青春惊慌失措 2020-12-20 02:11

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

body.style.backgrounColor and

wi         


        
4条回答
  •  半阙折子戏
    2020-12-20 02:25

    Using:

    body.style.backgroundColor
    

    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).

    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).

    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.

    Using:

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

    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).

提交回复
热议问题