How to dynamically add style rules in javascript W3C check_javascript skills

Source: Internet
Author: User
RubysLouvreblog is a series of excellent content. The following describes how to dynamically add style rules in javascript, and the final function allows your css to pass w3c verification. Undoubtedly, importing a new style sheet directly is the best option based on the separation of presentation and structure, but in some cases it won't work. For example, if we make a DIV that can be dragged, from the perspective of setting a style, we can definitely position it to avoid affecting the original document stream, and then slightly change its top and left values to achieve the moving effect. Since the drag concept is time, 24 frames per second, it is impossible for style sheets to write all of them. Therefore, it is necessary to dynamically generate style rules and quickly modify style rules. W3C has done a lot of work for this. In DOM2.0, many interfaces are added.

In the latter step, the separation of performance and structure does not only support importing style sheets. You must know that there are three types of styles: External styles, internal styles, and inline styles.

* The external style is the one we mentioned above, which is written in an independent CSS file.
* An internal style is written independently in a style label, which is usually placed in the head label. The style generated by the function I provided last is an internal style.
* Inline style is the style written in the style attribute of the element.

Newly Added interfaces are mainly concentrated in external styles. The reason is that the interfaces are implemented by the browser. Arrogant guys like IE6 never ignore their existence.

In W3C model, the link label and style label with type "text/css" represent a CSSStyleSheet object. styleSheets obtains all the CSSStyleSheet objects on the current page. However, this is a set rather than a simple array. Each CSSStyleSheet object has the following attributes,

* Type: returns the "text/css" string forever.
* Disabled: It works the same as the disabled of input. The default value is false.
* Href: Return URL. If the style label is null.
* Title: return the title value. The title is the same as the title of a common element.
* Media: IE is not the same as what Firefox returns. Media is used to specify which device the style rule is valid for. By default, it is all.
* OwnerRule: returns a read-only CSSRule object, if the style sheet is introduced with @ import.
* CssRules: returns a set of read-only style rule objects.

The style rule object (CSSStyleRule object) is developed by W3C to set styles in more detail. For example, the following content corresponds to a style rule object:

The Code is as follows:


Button [type] {
Padding: 4px 10px 4px 7px;
Line-height: 17px;
}


Style rule objects have the following attributes: type, cssText, parentStyleSheet, and parentRule.

Type is similar to the node's nodeType. It segments style rules. It uses an integer to represent its type. The details are as follows:

* 0: CSSRule. UNKNOWN_RULE
* 1: CSSRule. STYLE_RULE (defines a CSSStyleRule object)
* 2: CSSRule. CHARSET_RULE (defines a CSSCharsetRule object to set the character set of the current style table. It is the same as the current webpage by default)
* 3: CSSRule. IMPORT_RULE (to define a CSSImportRule object, use @ import to introduce other style sheets)
* 4: CSSRule. MEDIA_RULE (defines a CSSMediaRule object to set whether the style is used for display, printer, projector, and so on)
* 5: CSSRule. FONT_FACE_RULE (defines a CSSFontFaceRule object, @ font-face of CSS3)
* 6: CSSRule. PAGE_RULE (defines a CSSPageRule object)

CssText does not need to be said. It is a very useful attribute. It directly converts strings into style rules, regardless of the differences in style attributes of various browsers, such as cssFloat and styleFloat.

ParentStyleSheet and parentRule are both for @ import. However, @ import has a problem in IE, So I basically don't need it.

There are several ways to survive:

* NsertRule (rule, index): adds a style rule.
* DeleteRule (index): removes a style rule.
* GetPropertyValue (propertyName) gets the value of the corresponding style attribute of the element. If we get a style rule object, we can use CSSStyleRuleObject. getPropertyValue ("color") to get the font color settings. Compared with normal el. style. compared with the color method, the efficiency is quite high, because el. style. color gets inline styles, such as IE. If your element does not set the style attribute, you cannot get the prepared value. It may be blank or inhert ...... There may be compatibility issues, and this inline attribute is not necessarily the final style applied to elements, IE only calls less waste el. currentStyle [prop], other browsers call a very popular but troublesome document. defaultView. getComputedStyle (el, "") [prop].
* RemoveProperty (propertyName) removes the corresponding style attribute of the element.
* SetProperty (propertyName, value, priority) sets the element to add a style and specify the priority.

We can get a function to set the style:

The Code is as follows:


Var hyphenize = function (name ){
Return name. replace (/([A-Z])/g, "-$1"). toLowerCase ();
}

Var camelize = function (name ){
Return name. replace (/\-(\ w)/g, function (all, letter ){
Return letter. toUpperCase ();
});
}
Var setStyle = function (el, styles ){
For (var property in styles ){
If (! Styles. hasOwnProperty (property) continue;
If (el. style. setProperty ){
// It must be a hyphen, el. style. setProperty ('background-color', 'red', null );
El. style. setProperty (hyphenize (property), styles [property], null );
} Else {
// It must be a camper style, such as el. style. paddingLeft = "2em"
El. style [camelize (property)] = styles [property]
}
}
Return true;
}


Usage:

The Code is as follows:


SetStyle (p ,{
'Left': 0,
'Top': 0,
'Line-height': '2em ',
'Padding-Right': '4px'
});


However, I do not like this method very much. It generates an inline style, and it has to specially process float and opacity. In the inline style of IE7, there is also a Bug in the filter. Make sure to get it hasLayout. Otherwise, the filter will not take effect (we can check its status through el. currentStyle. hasLayout ). Therefore, cssText is better to be used as a single setting.

The addSheet method of my enhanced version is attached. It adds the ability to automatically process opacity, that is to say, we only need to set cssText according to the standard, it will automatically generate the corresponding filter, so that at least let Firefox and other browsers pass W3C verification.

The Code is as follows:


Var addSheet = function (){
Var doc, cssCode;
If (arguments. length = 1 ){
Doc = document;
CssCode = arguments [0]
} Else if (arguments. length = 2 ){
Doc = arguments [0];
CssCode = arguments [1];
} Else {
Alert ("addSheet function can accept up to two parameters! ");
}
If (! + "\ V1") {// new feature. You only need to enter the W3C transparent style, which is automatically converted to the transparent filter of IE.
Var t = cssCode. match (/opacity :( \ d? \. \ D + );/);
If (t! = Null ){
CssCode = cssCode. replace (t [0], "filter: alpha (opacity =" + parseFloat (t [1]) * 100 + ");");
}
}
CssCode = cssCode + "\ n"; // Add line breaks at the end to facilitate viewing in firebug.
Var headElement = doc. getElementsByTagName ("head") [0];
Var styleElements = headElement. getElementsByTagName ("style ");
If (styleElements. length = 0) {// if the style element does not exist, create
If (doc. createStyleSheet) {// ie
Doc. createStyleSheet ();
} Else {
Var tempStyleElement = doc. createElement ('style'); // w3c
TempStyleElement. setAttribute ("type", "text/css ");
HeadElement. appendChild (tempStyleElement );
}
}
Var styleElement = styleElements [0];
Var media = styleElement. getAttribute ("media ");
If (media! = Null &&! /Screen/. test (media. toLowerCase ())){
StyleElement. setAttribute ("media", "screen ");
}
If (styleElement. styleSheet) {// ie
StyleElement.styleSheet.css Text + = cssCode; // Add a new internal Style
} Else if (doc. getBoxObjectFor ){
StyleElement. innerHTML + = cssCode; // Firefox supports adding style sheet strings directly in innerHTML
} Else {
StyleElement. appendChild (doc. createTextNode (cssCode ))
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.