ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 6.1 Style Attribute (aka element inline CSS properties) Overview Every HTML element has a style attribute that can be used to inline CSS properties specific to the element. In the code below I am accessing the *style* attribute of a *`<div>`* that contains several inline CSS properties. live code: [http://jsfiddle.net/domenlightenment/A4Aph](http://jsfiddle.net/domenlightenment/A4Aph) ~~~ <!DOCTYPE html> <html lang="en"> <body> <div style="background-color:red;border:1px solid black;height:100px;width:100px;"></div> <script> var divStyle = document.querySelector('div').style; //logs CSSStyleDeclaration {0="background-color", ...} console.log(divStyle);  </script> </body> </html> ~~~ Notice in the code above that what is returned from the *style* property is a *CSSStyleDeclaration* object and not a string. Additionally note that only the elements inline styles (i.e. excluding the computed styles, computed styles being any styles that have cascaded from style sheets) are included in the *CSSStyleDeclartion* object. ## 6.2 Getting, setting, & removing individual inline CSS properties Inline CSS styles are individually represented as a property (i.e. object property) of the *style* object avaliabe on element node objects. This provides the interface for us to get, set, or remove individual CSS properties on an element by simply setting an objects property value. In the code below we set, get, and remove styles on a *`<div>`*by manipulating the properties of the *style* object. live code: [http://jsfiddle.net/domenlightenment/xNT85](http://jsfiddle.net/domenlightenment/xNT85) ~~~ <!DOCTYPE html> <html lang="en"> <body> <div></div> <script> var divStyle = document.querySelector('div').style; //set divStyle.backgroundColor = 'red'; divStyle.border = '1px solid black'; divStyle.width = '100px'; divStyle.height = '100px'; //get console.log(divStyle.backgroundColor); console.log(divStyle.border); console.log(divStyle.width); console.log(divStyle.height); /*remove divStyle.backgroundColor = ''; divStyle.border = ''; divStyle.width = ''; divStyle.height = ''; */ </script> </body> </html> ~~~ ### Notes The property names contained in the style object do not contain the normal hyphen that is used in CSS property names. The translation is pretty simple. Remove the hyphen and use camel case. (e.g. font-size = *fontSize* or background-image =*backgroundImage*). In the case where a css property name is a JavaScript keyword the javascript css property name is prefixed with "css" (e.g. float = *cssFloat*). Short hand properties are available as properties as well. So you can not only set *margin*, but also *marginTop*. Remember to include for any css property value that requires a unit of measure the appropriate unit  (e.g. *style.width = '300px';* *not style.width = '300';*). When a document is rendered in standards mode the unit of measure is require or it will be ignored. In quirksmode assumptions are made if not unit of measure is included. | CSS Property | JavaScript Property | | --- | --- | | background | background | | background-attachment | backgroundAttachment | | background-color | backgroundColor | | background-image | backgroundImage | | background-position | backgroundPosition | | background-repeat | backgroundRepeat | | border | border | | border-bottom | borderBottom | | border-bottom-color | borderBottomColor | | border-bottom-style | borderBottomStyle | | border-bottom-width | borderBottomWidth | | border-color | borderColor | | border-left | borderLeft | | border-left-color | borderLeftColor | | border-left-style | borderLeftStyle | | border-left-width | borderLeftWidth | | border-right | borderRight | | border-right-color | borderRightColor | | border-right-style | borderRightStyle | | border-right-width | borderRightWidth | | border-style | borderStyle | | border-top | borderTop | | border-top-color | borderTopColor | | border-top-style | borderTopStyle | | border-top-width | borderTopWidth | | border-width | borderWidth | | clear | clear | | clip | clip | | color | color | | cursor | cursor | | display | display | | filter | filter | | font | font | | font-family | fontFamily | | font-size | fontSize | | font-variant | fontVariant | | font-weight | fontWeight | | height | height | | left | left | | letter-spacing | letterSpacing | | line-height | lineHeight | | list-style | listStyle | | list-style-image | listStyleImage | | list-style-position | listStylePosition | | list-style-type | listStyleType | | margin | margin | | margin-bottom | marginBottom | | margin-left | marginLeft | | margin-right | marginRight | | margin-top | marginTop | | overflow | overflow | | padding | padding | | padding-bottom | paddingBottom | | padding-left | paddingLeft | | padding-right | paddingRight | | padding-top | paddingTop | | page-break-after | pageBreakAfter | | page-break-before | pageBreakBefore | | position | position | | float | styleFloat | | text-align | textAlign | | text-decoration | textDecoration | | text-decoration: blink | textDecorationBlink | | text-decoration: line-through | textDecorationLineThrough | | text-decoration: none | textDecorationNone | | text-decoration: overline | textDecorationOverline | | text-decoration: underline | textDecorationUnderline | | text-indent | textIndent | | text-transform | textTransform | | top | top | | vertical-align | verticalAlign | | visibility | visibility | | width | width | | z-index | zIndex | The style object is a *CSSStyleDeclaration* object and it provides not only access to inidividual CSS properties, but also the *setPropertyValue(propertyName)*, *getPropertyValue(propertyName,value)*, and*removeProperty()* methods used to manipulate individual CSS properties on a element node. In the code below we set, get, and remove individual CSS properties on a *`<div>`* using these methods. live code: [http://jsfiddle.net/domenlightenment/X2DyX](http://jsfiddle.net/domenlightenment/X2DyX) ~~~ <!DOCTYPE html> <html lang="en"> <head> <style> </style> </head> <body> <div style="background-color:green;border:1px solid purple;"></div> <script> var divStyle = document.querySelector('div').style; //set divStyle.setProperty('background-color','red'); divStyle.setProperty('border','1px solid black'); divStyle.setProperty('width','100px'); divStyle.setProperty('height','100px'); //get console.log(divStyle.getPropertyValue('background-color')); console.log(divStyle.getPropertyValue('border','1px solid black')); console.log(divStyle.getPropertyValue('width','100px')); console.log(divStyle.getPropertyValue('height','100px')); /*remove divStyle.removeProperty('background-color'); divStyle.removeProperty('border'); divStyle.removeProperty('width'); divStyle.removeProperty('height'); */ </script> </body> </html> ~~~ ### Notes Take notice that the property name is passed to the *setProperty()* and *getPropertyValue()* method using the css property name including a hyphen (e.g. *background-color* not *backgroundColor*). For more detailed information about the *setProperty()*, *getPropertyValue()*, and *removeProperty()* as well as additional properties and methods have a look the [documentation](https://developer.mozilla.org/en/DOM/CSSStyleDeclaration) provided by Mozilla. ## 6.3 Getting, setting, & removing all inline CSS properties Its possible using the *cssText* property of the *CSSStyleDeclaration* object as well as the *getAttribute()* and*setAttribute()* method to get, set, and remove the entire (i.e. all inline CSS properties) value of the style attribute using a JavaScript string. In the code below we get, set, and remove all inline CSS (as opposed to individually changing CSS proeprties) on a *`<div>`*. live code: [http://jsfiddle.net/domenlightenment/wSv8M](http://jsfiddle.net/domenlightenment/wSv8M) ~~~ <!DOCTYPE html> <html lang="en"> <body> <div></div> <script> var div = document.querySelector('div'); var divStyle = div.style; //set using cssText divStyle.cssText = 'background-color:red;border:1px solid black;height:100px;width:100px;'; //get using cssText console.log(divStyle.cssText); //remove divStyle.cssText = ''; //exactly that same outcome using setAttribute() and getAttribute() //set using setAttribute div.setAttribute('style','background-color:red;border:1px solid black;height:100px;width:100px;'); //get using getAttribute console.log(div.getAttribute('style')); //remove div.removeAttribute('style'); </script> </body> </html> ~~~ ### Notes If its not obvious you should note that replacing the *style* attribute value with a new string is the fastest way to make multiple changes to an elements style. ## 6.4 Getting an elements computed styles (i.e. actual styles including any from the cascade) using *getComputedStyle()* The *style* property only contains the css that is defined via the style attribute. To get an elements css from the cascade (i.e. cascading from inline style sheets, external style sheets, browser style sheets) as well as its inline styles you can use *getComputedStyle()*. This method provides a read-only *CSSStyleDeclaration* object similar to *style*. In the code example below I demonstrate the reading of cascading styles, not just element inline styles. live code: [http://jsfiddle.net/domenlightenment/k3G5Q](http://jsfiddle.net/domenlightenment/k3G5Q) ~~~ <!DOCTYPE html> <html lang="en"> <head> <style> ​div{ background-color:red; border:1px solid black; height:100px; width:100px; } </style> </head> <body> <div style="background-color:green;border:1px solid purple;"></div> <script> var div = document.querySelector('div'); //logs rgb(0, 128, 0) or green, this is an inline element style console.log(window.getComputedStyle(div).backgroundColor); //logs 1px solid rgb(128, 0, 128) or 1px solid purple, this is an inline element style console.log(window.getComputedStyle(div).border); //logs 100px, note this is not an inline element style console.log(window.getComputedStyle(div).height); //logs 100px, note this is not an inline element style console.log(window.getComputedStyle(div).width); </script> </body> </html> ~~~ Make sure you note that *getComputedStyle()* method honors the [CSS specificity hierarchy](http://css-tricks.com/specifics-on-css-specificity/). For example in the code just shown the *backgroundColor* of the *`<div>`* is reported as green not red because inline styles are at the top of the specificity hierarchy thus its the inline *backgroundColor* value that is applied to the element by the browser and consider its final computed style. ### Notes No values can by set on a *CSSStyleDeclaration* object returned from *getComputedStyles()* its read only. The *getComputedStyles()* method returns color values in the *rgb(#,#,#)* format regardless of how they were originally authored. [Shorthand](http://www.w3.org/TR/CSS21/about.html#shorthand) properties are not computed for the *CSSStyleDeclaration* object you will have to use non-shorthand property names for property access (e.g. marginTop not margin)*.* ## 6.5 Apply & remove css properties on an element using *class* & *id*attributes Style rules defined in a inline style sheet or external style sheet can be added or removed from an element using the *class* and *id* attribute. This is a the most common pattern for manipulating element styles. In the code below, leveraging *setAttribute()* and *classList.add(),* inline style rules are applied to a *`<div>`* by setting the*class* and *id* attribute value. Using *removeAttribute()* and *classList.remove()* these CSS rules can be removed as well. live code: [http://jsfiddle.net/domenlightenment/BF9gM](http://jsfiddle.net/domenlightenment/BF9gM) ~~~ <!DOCTYPE html> <html lang="en"> <head> <style> .foo{  background-color:red;  padding:10px;}#bar{  border:10px solid #000;  margin:10px;} </style> </head> <body> <div></div> <script> var div = document.querySelector('div'); //set div.setAttribute('id','bar'); div.classList.add('foo'); /*remove div.removeAttribute('id'); div.classList.remove('foo'); */ </script> </body> </html> ~~~