16.3 Scripting Inline Styles
e.style.fontSize = "24pt"; e.style.fontWeight = "bold"; e.style.color = "blue";
Many CSS style properties, such as font-size, contain hyphens in their names. In Java-Script, a hyphen is interpreted as a minus sign, so it is not possible to write an expression like:
e.style.font-size = "24pt"; // Syntax error!
e.style.fontFamily = "sans-serif";
16.3 Scripting Inline Styles | 431
When working with the style properties of the CSSStyleDeclaration object, remember that all values must be specified as strings. In a stylesheet or style attribute, you can write:
position: absolute; font-family: sans-serif; background-color: #ffffff;
e.style.position = "absolute"; e.style.fontFamily = "sans-serif"; e.style.backgroundColor = "#ffffff";
Furthermore, remember that all the positioning properties require units. Thus, it is not correct to set the left property like this: e.style.left = 300; // Incorrect: this is a number, not a string e.style.left = "300"; // Incorrect: the units are missing
e.style.left = "300px";
If you want to set the left property to a computed value, be sure to append the units at the end of the computation:
e.style.left = (x0 + left_margin + left_border + left_padding) + "px";
Notice that the numeric result of the computation will be converted to a string as a side effect of appending the units string.
Recall that some CSS properties, such as margin, are shortcuts for other properties, such as margin-top, margin-right, margin-bottom, and margin-left. The CSSStyleDeclaration object has properties that correspond to these shortcut properties. For example, you might set the margin property like this:
e.style.margin = topMargin + "px " + rightMargin + "px " + bottomMargin + "px " + leftMargin + "px";
Arguably, it is easier to set the four margin properties individually:
e.style.marginTop = topMargin + "px"; e.style.marginRight = rightMargin + "px";
e.style.marginBottom = bottomMargin + "px";
e.style.marginLeft = leftMargin + "px";
Reading the inline style of an element is particularly difficult for style properties that require units and for shortcut properties: your code has to include nontrivial CSS parsing capabilities to really make use of those values. In general, the inline style of an element is only useful for setting styles. If you need to query the style of an element, use the computed style, which is discussed in §16.4 .
Sometimes, you may find it easier to set or query the inline style of an element as a single string value rather than as a CSSStyleDeclaration object. To do that, you can use the Element getAttribute() and setAttribute() methods, or you can use the cssText property of the CSSStyleDeclaration object:
// Set the style attribute of e to the string s with either of these lines: e.setAttribute("style", s); e.style.cssText = s;欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27728.html