MDN’s new design is in Beta! A sneak peek:

翻譯不完整。請協助 翻譯此英文文件

The property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.The style property has the same (and highest) priority in the CSS cascade as an inline style declaration set via the style attribute.

設定 styles

Styles can be set by assigning a string directly to the style property (as in = "color: blue;") or by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in = '...' ) as using = '...' or elt.setAttribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using<property> (i.e., not


// Set multiple styles in a single statement = "color: blue; border: 1px solid black"; 
// OR
elt.setAttribute("style", "color:red; border: 1px solid blue;"); = "blue";  // Set specific style while leaving other inline style values untouched


The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. To get the values of all CSS properties for an element you should use window.getComputedStyle() instead.

The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the computedStyle() method:

 <body style="font-weight:bold;">

    <div style="color:red" id="myElement">..</div>

var element = document.getElementById("myElement");
var out = "";
var elementStyle =;
var computedStyle = window.getComputedStyle(element, null);

for (prop in elementStyle) {
  if (elementStyle.hasOwnProperty(prop)) {
    out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";

The output would be something like:

fontWeight = '' > 'bold'
color = 'red' > 'rgb(255, 0, 0)'

Note the presence of the value "bold" for font-weight in the computed style and the absence of it in the element's style property


DOM Level 2 Style:


Note: Starting in Gecko 2.0, you can set SVG properties' values using the same shorthand syntax. For example: = 'lime';



 此頁面的貢獻者: jackblackevo
 最近更新: jackblackevo,