Add style rules dynamically

Source: Internet
Author: User

I used to provide a useful function in a blog post, which is widely used in my blog posts. I recently read a lot of things, so I had this blog post to sort out the new things I learned.

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 value of the title. 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:

 
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): Add 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:

VaR hyphenize = function (name) {return name. replace (/([A-Z])/g, "-$1 "). tolowercase ();} var camw.e = 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 {// The camper style, such as El. style. paddingleft = "2em" El. style [camelize (property)] = styles [property]} return true ;}

Usage:

 
Setstyle (DIV, {'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, or the filter will not take effect (we can passEl. currentstyle. haslayoutView its status ). 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.

// 2010.01.27 update situ zhengmei var addsheet = function (CSS) {If (! -[1,]) {CSS = CSS. Replace (/opacity: \ s * (\ D? \. \ D +)/g, function ($, $1) {$1 = parsefloat ($1) * 100; if ($1 <0 | $1> 100) return ""; Return "filter: alpha (opacity =" + $1 + ");"});} CSS + = "\ n"; // Add a line break at the end, it is easy to view in firebug. VaR Doc = Document, head = Doc. getelementsbytagname ("head") [0], Styles = head. getelementsbytagname ("style"), style, media; If (styles. length = 0) {// If the style element does not exist, create if (Doc. createstylesheet) {// ie Doc. createstylesheet ();} else {style = Doc. createelement ('style'); // W3C style. setattribute ("type", "text/CSS"); head. insertbefore (style, null)} style = styles [0]; media = style. getattribute ("Media"); If (Me Dia === null &&! /Screen/I. test (media) {style. setattribute ("Media", "all");} If (style. stylesheet) {// ie style.stylesheet.css text + = CSS; // Add a new internal style} else if (Doc. getboxobjectfor) {style. innerhtml + = CSS; // Firefox supports adding style sheet strings directly to innerhtml} else {style. appendchild (Doc. createtextnode (CSS ))}}

Some netizens asked why they should prioritize the use of existing style sheets to add new style rules, because there are the following restrictions in IE (including IE6, IE7, and IE8 beta1:

    1. Only the first 31 links or CSS associated with style labels can be applied in this document.
      Starting from 32nd, all associated CSS tags will be invalid. Internet Explorer official documentation all style tags after the first 30 style tags on an HTML page are not applied in Internet Explorer also mentions this restriction, including in use.. XML files also have this restriction.
    2. A style tag is only valid for the first 31 @ import commands.Ignore from 32nd @ import commands.
    3. A css file is only valid for the first 31 @ import commands.Ignore from 32nd @ import commands.
    4. The number of separators in each style label or CSS file in IE cannot exceed 4095.
    5. @ Import: the number of layers under the command cannot exceed 4When the CSS file is introduced using the @ import command in IE, the layer 5th fails. This restriction comes from Cascade limit via @ import rule. In fact, the browser does not fully support multi-layer nesting, so even if you have to use the @ import command to introduce CSS files, there should be no more than two layers.

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.