Another talk on JavaScript dynamic adding style rules _javascript skills of the campus inspection

Source: Internet
Author: User
There is no doubt that, based on the principle of separation of performance and structure, direct import of a new style sheet is the best choice, but in some cases, such as we do a drag div, from the point of view of the set style, it is absolutely positioned to prevent the original document flow, And then a little bit to change the value of its top and left to achieve the effect of moving. Because the drag is a time concept, 24 frames a second, the stylesheet cannot be written in every way. Therefore, it is necessary to dynamically generate style rules and quickly modify style rules, and the DOM2.0 has done a lot of work in this respect, and has expanded many interfaces in the process.

To step back, the performance is separated from the structure and more than the way to import the stylesheet. You know, there are three types of styles, external styles, internal styles, and inline styles.

* External style, is the one we said above, written in a separate CSS file.
* Internal style, which is written independently in a style label, usually in the head tag, and the function I provide finally produces is the internal style.
* Inline style, which is the style written in the element's style property.

The newly added interfaces are mainly concentrated in the external style-the interface, because the corresponding implementation is provided by the browser side, arrogant fellow like IE6, never ignoring their existence.

In the model of the TEXT/CSS, the link tag and style label of type "" are all representative of a Cssstylesheet object, we can pass Document.stylesheets Get all the Cssstylesheet objects on the current page, but this is a collection, not a simple array. Each Cssstylesheet object has the following properties,

* Type: Returns the "Text/css" string forever.
* Disabled: The same effect as input disabled, default is False.
* href: Returns the URL if the style label is null.
* Title: Return the title of the value, title and ordinary elements of the title is the same, whatever you write.
* Media:ie and Firefox return things are not consistent, not too much to say. Media is used to specify which style rules it has for which devices are valid, by default.
* Ownerrule: Returns a read-only Cssrule object if the stylesheet is introduced with @import.
* Cssrules: Returns a collection of read-only style rule objects (Cssstylerule object).

The Style Rule object (Cssstylerule object), which is created by the whole of the Consortium for more detailed styling of a style, is a style rule object that corresponds to the following:
Copy Code code as follows:

Button[type] {
padding:4px 10px 4px 7px;
line-height:17px;
}

Style rule objects have the following key attributes: Type,csstext,parentstylesheet,parentrule.

Type is somewhat similar to the nodetype of a node, which breaks down the style rule by using an integer to represent its type. The specific situation is as follows

* 0:cssrule.unknown_rule
* 1:cssrule.style_rule (Define a Cssstylerule object)
* 2:cssrule.charset_rule (defines a Csscharsetrule object that is used to set the character set of the current style sheet, the default is the same as the current page)
* 3:cssrule.import_rule (Define a Cssimportrule object, which is to introduce other stylesheets with @import)
* 4:cssrule.media_rule (defines a Cssmediarule object that is used to set this style for display, printer, projector, etc.)
* 5:cssrule.font_face_rule (defines a Cssfontfacerule object, CSS3 @font-face)
* 6:cssrule.page_rule (Define a Csspagerule object)

Csstext Needless to say, a very useful attribute that directly converts strings into style rules, ignoring the differences in browser style attributes, such as Cssfloat and stylefloat.

Parentstylesheet and Parentrule are all for @import. However, @import in IE under the problem, I basically do not use it.

There are a few untimely ways:

* 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 take advantage of cssstyleruleobject. GetPropertyValue ("Color") gets the settings for its font color. Compared with the ordinary El.style.color method, its efficiency is quite high, because El.style.color gets the inline style, like ie the geek, if your element does not set the style attribute, cannot get the prepared value, may be empty, may be inhert ... There may also be compatibility issues, and the inline attribute is not necessarily the style that ultimately applies to the element, ie only calls a less-than-waste el.currentstyle[prop], and the other browsers invoke a fairly promising but troublesome document. DefaultView. getComputedStyle (el, "") [prop].
* Removeproperty (PropertyName) removes the corresponding style attributes for the element.
* SetProperty (propertyname,value,priority) Set element to add a style, but also to specify the priority level.

We can get a set-style function to come out:
Copy Code code 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) {
Must be hyphen style, el.style.setProperty (' Background-color ', ' red ', null);
El.style.setProperty (Hyphenize (property), Styles[property],null);
} else {
Must be a hump style, such as El.style.paddingLeft = "2em"
El.style[camelize (property)] = Styles[property]
}
}
return true;
}

How to use:
Copy Code code as follows:

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

But I do not like this method, generated is inline style, it also has to deal with the special float and opacity. In the IE7 inline style, the filter also has a bug, make sure it gets haslayout, or the filter doesn't take effect (we can view its status by El.currentStyle.hasLayout). Therefore, if it is set, it is better to use csstext catch.

Finally attach my enhanced version of the Addsheet method. It adds the ability to automate the processing of opacity, which means that we only need to set the csstext according to the standard, it will automatically generate the corresponding filter, so that at least let Firefox and other browsers through the campus check.
Copy Code code 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 accepts up to two arguments!");
}
if (!+ "\v1") {//new features, users simply enter the transparent style of the net, it will automatically convert to IE transparent filter
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 end to facilitate viewing under Firebug.
var headelement = Doc.getelementsbytagname ("head") [0];
var styleelements = headelement.getelementsbytagname ("style");
if (Styleelements.length = = 0) {//If a STYLE element is not present, 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.cssText + = csscode;//Add a new inner style
}else if (doc.getboxobjectfor) {
styleelement.innerhtml + + csscode;//Firefox support direct InnerHTML add a style table string
}else{
Styleelement.appendchild (Doc.createtextnode (Csscode))
}
}
Related Article

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.