12.2.1 Styles for Accessing Elements [Advanced JavaScript Programming 3rd Edition]

Any HTML element that supports the style attribute has a corresponding style attribute in JavaScript. This style object is an instance of CSSStyleDeclaration and contains all the style information specified through the HTML style attribute, but does not contain styles cascaded from external or embedded style sheets. Any CSS properties specified in the style attribute will behave as corresponding properties of this style object. CSS property names that use dashes (separating different words, such as background-image) must be converted to camel case before they can be accessed by JavaScript. The following table lists several common CSS properties and their corresponding property names in the style object.


 
In most cases, the conversion can be achieved by simply changing the format of the property name. One of the CSS properties that cannot be converted directly is float. Since float is a reserved word in JavaScript, it cannot be used as a property name. The "DOM2-level styles" specification states that the corresponding property name on the style object should be cssFloat; Firefox, Safari, Opera, and Chrome all support this property, while IE supports styleFloat.
As long as you get a reference to a valid DOM element, you can style it with JavaScript at any time. Here are a few examples.

var myDiv = document.getElementById("myDiv");
//set background color
myDiv.style.backgroundColor = "red";
// change size
myDiv.style.width = "100px";
myDiv.style.height = "200px";
//specify border
myDiv.style.border = "1px solid black";

When changing styles in this way, the appearance of the element is automatically updated.

In standard mode, all measures must specify a unit of measure. In promiscuous mode, you can set style.width to "20" and the browser will assume it is "20px"; but in standard mode, setting style.width to "20" will cause it to be ignored - because there is no measure unit. In practice, it is best to always specify the unit of measure.

The style specified in the style attribute can also be obtained through the style object. Take the following HTML code as an example.

<div id="myDiv" style="background-color:blue; width:10px; height:25px"></div>

The style information specified in the style attribute can be obtained with the following code.

alert(myDiv.style.backgroundColor); //"blue"
alert(myDiv.style.width); //"10px"
alert(myDiv.style.height); //"25px"

If the style attribute is not set for an element, the style object may contain some default values, but these values ​​do not accurately reflect the style information of the element.

1. DOM style properties and methods

The "DOM2-level styles" specification also defines some properties and methods for the style object. These properties and methods can also modify the style while providing the value of the element's style attribute. These properties and methods are listed below.

  • cssText: As mentioned earlier, it provides access to the CSS code in the style attribute.
  • length: The number of CSS properties applied to the element.
  • parentRule: A CSSRule object representing CSS information. The CSSRule type is discussed later in this section.
  • getPropertyCSSValue(propertyName): Returns a CSSValue object containing the given property value.
  • getPropertyPriority(propertyName): Returns "important" if the given property is set with !important; otherwise, returns an empty string.
  • getPropertyValue(propertyName): Returns the string value of the given property.
  • item(index): Returns the name of the CSS property at the given position.
  • removeProperty(propertyName): Removes the given property from the style.
  • setProperty(propertyName,value,priority): Sets the given property to the corresponding value, plus the priority flag ("important" or an empty string).

The CSS code in the style attribute can be accessed through the cssText property. In read mode, cssText returns the browser's internal representation of the CSS code in the style attribute. In write mode, the value assigned to cssText overrides the value of the entire style attribute; that is, any style information previously specified through the style attribute is lost. For example, if you set a border on an element via the style attribute, and then rewrite cssText with a rule that does not include a border, the border on the element will be erased. Below is an example of using the cssText property.

myDiv.style.cssText = "width: 25px; height: 100px; background-color: green";
alert(myDiv.style.cssText);

Setting cssText is the quickest way to apply multiple changes to an element, since all changes can be applied at once.
The length property is designed to be used with the item() method to iterate over the CSS properties defined in the element.
When using length and item(), the style object is actually equivalent to a collection, and you can use the square bracket syntax instead of item() to get the CSS property at a given position, as shown in the following example.

for (var i=0, len=myDiv.style.length; i < len; i++){
    alert(myDiv.style[i]); //或者myDiv.style.item(i)
}

The CSS property name ("background-color", not "backgroundColor") can be obtained either using the square bracket syntax or using the item() method. Then, you can use the obtained property name in getPropertyValue() to further get the value of the property, as shown below.

var prop, value, i, len;
for (i = 0, len = myDiv.style.length; i < len; i++) {
	prop = myDiv.style[i]; //或者 myDiv.style.item(i)
	value = myDiv.style.getPropertyValue(prop);
	alert(prop + " : " + value);
}

The getPropertyValue() method is always a string representation of the CSS property value. If you need more information, you can use the getPropertyCSSValue() method, which returns a CSSValue object containing two properties: cssText and cssValueType. Among them, the value of the cssText property is the same as the value returned by getPropertyValue(), and the cssValueType property is a numeric constant indicating the type of the value: 0 for inherited value, 1 for basic value, 2 for list of values, and 3 for custom value of . The following code outputs both the CSS property value and the type of the value.

var prop, value, i, len;
for (i = 0, len = myDiv.style.length; i < len; i++) {
	prop = myDiv.style[i]; //或者myDiv.style.item(i)
	value = myDiv.style.getPropertyCSSValue(prop);
	alert(prop + " : " + value.cssText + " (" + value.cssValueType + ")");
}

Run it
In actual development, getPropertyCSSValue() is used much less than getPropertyValue(). IE9+, Safarie3+ and Chrome support this method. Firefox 7 and earlier also provided this access, but the call always returned null.
To remove a CSS property from an element's styles, use the removeProperty() method. Using this method to remove a property means that the default style (cascaded from other style sheets) will be applied to the property. For example, to remove the border property set via the style attribute, use the following code.

myDiv.style.removeProperty("border");

Use this method when you are not sure what default value a given CSS property has. A default value can be applied to an element as long as the corresponding attribute is removed.

Unless otherwise noted, the properties and methods discussed in this section are supported by IE9+, Firefox, Safari, Opera 9+, and Chrome.

2. Calculation style

While the style object can provide style information for any element that supports the style attribute, it does not contain style information that cascades from other style sheets and affects the current element. "DOM2-level styles" enhances document.defaultView to provide the getComputedStyle() method. This method accepts two parameters: the element to get the computed style from and a pseudo-element string (eg ":after"). The second parameter can be null if pseudo-element information is not required. The getComputedStyle() method returns a CSSStyleDeclaration object (of the same type as the style property) containing all computed styles for the current element.
Take the following HTML page as an example.

<!DOCTYPE html>
<html>
	<head>
		<title>
			Computed Styles Example
		</title>
		<style type="text/css">
			#myDiv { background-color: blue; width: 100px; height: 200px; }
		</style>
	</head>
	<body>
		<div id="myDiv" style="background-color: red; border: 1px solid black">
		</div>
	</body>
</html>

Run it
. The styles applied to the <div> element in this example come from the embedded style sheet (the styles in the <style> element) on the one hand, and its style attribute on the other hand. However, the backgroundColor and border are set in the style attribute, but not the width and height, which are applied through style sheet rules. The following code can get the calculated style of this element.

var myDiv = document.getElementById("myDiv");
var computedStyle = document.defaultView.getComputedStyle(myDiv, null);
alert(computedStyle.backgroundColor); // "red"
alert(computedStyle.width); // "100px"
alert(computedStyle.height); // "200px"
alert(computedStyle.border); // "1px solid black" in some browsers

Run it
. In the computed style of this element, the value of the background color is "red", the value of the width is "100px", and the value of the height is "200px". We notice that the background color is not "blue" because this style has been overridden in its own style attribute. The border property may or may not return the actual border rules in the stylesheet (Opera does, but other browsers do not). The reason for this difference is that different browsers interpret rollup properties (like border) differently, since setting this property actually involves many other properties. When setting the border, you actually set the border width, color, and style properties of the four sides ( border-left-width , border-top-color , border-bottom-style , etc.). So even though computedStyle.border doesn't return a value in all browsers, computedStyle.borderLeftWidth does.

Note that even though some browsers support this feature, the way the value is represented may differ. For example, Firefox and Safari will convert all colors to RGB format (eg red is rgb(255,0,0)). Therefore, when using the getComputedStyle() method, it is best to test it in several browsers.

IE does not support the getComputedStyle() method, but it has a similar concept. In IE, every element with a style attribute also has a currentStyle attribute. This property is an instance of CSSStyleDeclaration that contains all computed styles for the current element. The way to obtain these styles is similar, as shown in the following example.

var myDiv = document.getElementById("myDiv");
var computedStyle = myDiv.currentStyle;
alert(computedStyle.backgroundColor); //"red"
alert(computedStyle.width); //"100px"
alert(computedStyle.height); //"200px"
alert(computedStyle.border); //undefined

Running it
Like the DOM version, IE doesn't return the border style either, because it's a composite property.
Regardless of the browser, the most important thing to remember is that all computed styles are read-only; CSS properties in the computed style object cannot be modified. In addition, computed styles also contain style information that belongs to the browser's internal style sheet, so any CSS properties with default values ​​will be reflected in the computed styles. For example, the visibility property in all browsers has a default value, but this value varies by implementation. By default, some browsers set the visibility property to "visible", while others set it to "inherit". In other words, you cannot expect the default value of a CSS property to be the same across browsers. If you need an element to have a specific default value, you should manually specify that value in the stylesheet.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326686642&siteId=291194637