There are three ways to define styles in HTML: Include external style sheet files through the <link/> element (external style sheets), use <style/> elements to define inline styles (inline style sheets), Use the style attribute to define a style for a specific element (inline style sheet).
The ability to determine whether the browser supports DOM2-level defined CSS can be used
document.implementation.hasFeature ("Css2", "2.0"); Support returns TRUE, does not support return false
1. Accessing element styles
Any HTML element that supports the style attribute has a corresponding style attribute in JavaScript that can be used to get and set inline styles, but not to get and set external and inline styles. In CSS, the "-" linked attributes are changed to hump-case form. But float cannot (because it is reserved word), except in IE is stylefloat, other browsers are cssfloat.
var divnode=document.getelementbyid ("mydiv");d ivnode.style.backgroundColor= "Pink"; // set the background of the element with ID mydiv to red divnode.style.height= "100px"; // Set Height
Because the inline style has a high precedence, the same CSS properties in the external and embedded styles are overwritten after the setting.
<id= "mydiv" style= "background-color:pink;height:100px;" ></ Div >
alert (Divnode.style.backgroundColor); // "Pink"alert (divnode.style.height); // "100px"alert (divnode.style.width); // "" (where width is not in inline style, so returns a null character.)
The style object also has the following properties and methods.
- Csstext: Access to CSS code in the style attribute
- Length: Number of CSS properties applied
- Parentrule: The Cssrule object that represents the CSS information.
- Getpropertycssvalue (PropertyName): Fan Hu contains a given property worth Cssvalue object.
- Getpropertypriority (PropertyName): returns "Important" if the given property uses the!important setting; otherwise, an empty string is returned.
- GetPropertyValue (PropertyName): returns the string value of the given property .
- Item (Index): Returns the CSS property name for the given location.
- Removeproperty (PropertyName): removes the specified attribute from the style .
- SetProperty (propertyname,value,priority): sets the appropriate value for the given property and adds a priority flag ("important" or an empty string)
While a style object can provide style information for any element that supports the style attribute, it does not include the other two styles overlay and affect the style information of the current element
Document.defaultView.getComputedStyle (element, pseudo-element string); Null if no pseudo element is required. Returns a Cssstyledeclaration object that contains the calculated style of the element (with the default style). IE does not support
#mydiv { Border: 2px blue solid; }
You can also get other CSS properties to the element, but the content returned is browser-dependent. You can test it.
Dom Access element styles and manipulate element styles