Add CSS style sheet files dynamically using JS Functions

Source: Internet
Author: User

The function is provided first. Copy codeThe Code is as follows: varaddSheet = function (){
Vardoc, cssCode;
If (arguments. length = 1 ){
Doc = document;
CssCode = arguments [0]
} Elseif (arguments. length = 2 ){
Doc = arguments [0];
CssCode = arguments [1];
} Else {
Alert ("addSheet function can accept up to two parameters! ");
}
If (! + "V1") {// added the automatic conversion transparency function. You only need to enter the W3C transparent style, which will be automatically converted to the IE transparent filter.
Vart = cssCode. match (/opacity :( d ?. D + );/);
If (t! = Null ){
CssCode = cssCode. replace (t [0], "filter: alpha (opacity =" + parseFloat (t [1]) * 100 + ")")
}
}
CssCode = cssCode + ""; // Add line breaks at the end to facilitate viewing in firebug.
VarheadElement = doc. getElementsByTagName ("head") [0];
VarstyleElements = headElement. getElementsByTagName ("style ");
If (styleElements. length = 0) {// if the style element does not exist, create
If (doc. createStyleSheet) {// ie
Doc. createStyleSheet ();
} Else {
VartempStyleElement = doc. createElement ('style'); // w3c
TempStyleElement. setAttribute ("type", "text/css ");
HeadElement. appendChild (tempStyleElement );
}
}
VarstyleElement = styleElements [0];
Varmedia = styleElement. getAttribute ("media ");
If (media! = Null &&! /Screen/. test (media. toLowerCase ())){
StyleElement. setAttribute ("media", "screen ");
}
If (styleElement. styleSheet) {// ie
StyleElement.styleSheet.css Text + = cssCode;
} Elseif (doc. getBoxObjectFor ){
StyleElement. innerHTML + = cssCode; // Firefox supports adding style sheet strings directly in innerHTML
} Else {
StyleElement. appendChild (doc. createTextNode (cssCode ))
}
}

Sometimes we need to dynamically introduce some CSS styles to the document in the. js file. For some short CSS code, we can call its style method, suchCopy codeThe Code is as follows: varddd = document. getElementById ("ddd ");
Ddd. style. border = "1 pxsolidred ";

It doesn't matter if it is longer:Copy codeThe Code is as follows: varddd = document. getElementById ("ddd ");
Ddd.style.css Text = "border: 1 pxsolidred; color: #000; background: #444; float: left ";

For me, I like the latter. Because the former has serious compatibility problems. For example, float is styleFloat in IE and cssFloat in W3C standard browsers such as Firefox. CssText is a wildcard.
If it is too long, we can dynamically import a CSS file. For exampleCopy codeCode: functionaddSheetFile (path ){
Varfileref = document. createElement ("link ")
Fileref. rel = "stylesheet ";
Fileref. type = "text/css ";
Fileref. href = path;
Fileref. media = "screen ";
Varheadobj = document. getElementsByTagName ('head') [0];
Headobj. appendChild (fileref );
}

This function is a little cumbersome in IE. I have always used the native function of the browser that is used by the browser that supports the most efficient binary code.Copy codeThe Code is as follows: varoStylesheet = document. createStyleSheet (sURL, iIndex );

The two parameters in createStyleSheet are optional.
But if our style is exclusive to a page and can only be used by administrators, and that part of the page is dynamically generated, do we need to introduce it from the very beginning? Need a specific file to load it? The best way is to bind these styles with dynamic scripts. I developed this function for this purpose.
Frankly speaking, it was initially developed for the rich text editor. As we all know, the most popular method of rich text input boxes is to put the content to be input into iframe, which involves two kinds of documents, one on the homepage and the other on the iframe document. Iframe document also involves compatibility issues. We can:
Variframe = document. createElement ('iframe'); // generate the richtexteditor for editing.
VariframeDocument = iframe. contentDocument | iframe.content#doc ument;
......
Well, it's far away. All in all, the initial determination of the function is to prepare for the two documents. If the iframe is not involved, we can pass in only one parameter. The last parameter is always a CSS string.
Then, the styleSheet element is dynamically generated to add the CSS string to this element. Of course, if there is a current stage, it will certainly be ready-made. The more DOM elements, the greater the burden on the browser. We think of the document. styleSheets method. It returns a set that contains the style and link elements. It also involves compatibility issues, such:Copy codeThe Code is as follows: <! DOCTYPEhtmlPUBLIC "-// W3C // DTDXHTML1.0Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Htmlxmlns ="
<Head>
<Metahttp-equiv = "content-type" content = "text/html; charsets = UTF-8"/>
<% # Force IE8 to display the webpage like IE7-%>
<Metahttp-equiv = "X-UA-Compatible" content = "IE = EmulateIE7"/>
<% # -- All links are opened in this window by default-%>
<Basetarget = "_ self"/>
<Title> <% = h (yield (: title) | controller. action_name %> </title>
<% = Stylesheet_link_tag "screen", "button", "style" %>
<Linkrel = "stylesheet" href = "/stylesheets/print.css" type = "text/css" media = "print">
<! -- [IfltIE8]>
<Linkrel = "stylesheet" href = "/stylesheets/ie.css" type = "text/css" media = "screen">
<! [Endif] -->
<% = Javascript_tag "window. _ token = '# {form_authenticity_token}'" ifActionController: Base. allow_forgery_protection %>
<% = Javascript_include_tag: defaults %>
<Styletype = "text/css" media = "print"> </style>
</Head>

The above uses alert (document. styleSheets. length); test, IE returns 6, W3C explorer returns 5. Therefore, it was rejected. In addition, we only use style elements and do not use external links. The second part of the determination is for the style element in the head, and no one is created. Then we can add the CSS string to the first style element.
Next, we need to apply an insurance lock, because when media = "print", the defined effect is valid only when the page is printed. To prevent the media Value of the first style element from being screen, we have to change it.Copy codeThe Code is as follows: varstyleElement = styleElements [0];
Varmedia = styleElement. getAttribute ("media ");
If (media! = Null &&! /Screen/. test (media. toLowerCase ())){
StyleElement. setAttribute ("media", "screen ");
}

Some media instructions are attached.
Screen (default), submitted to the computer screen;
Print, output to the printer;
Projection, submitted to the projector;
Aural, speaker;
Braille, submitted to the convex-text tactile sensing device;
Tty, telex typewriter (using a fixed font );
TV, TV set;
All, all output devices.
The last question is how to add it. It can be divided into IE, Firefox and other browsers. The browser can also use its own private attributes or methods. For example, styleSheet is used exclusively by IE, and getBoxObjectFor is used exclusively by firefox (of course you can also use it (/firefox /. test (navigator. userAgent. toLowerCase (). Generally, DOM operations are the most time-consuming and private operations can be used!
Usage.Copy codeThe Code is as follows: addSheet ("
. RTE_iframe {width: 600px; height: 300px ;}
. RTE_toolbar {width: 600px ;}
. Color_result {width: 216px ;}
. Color_view {width: 110px; height: 25px ;}
. Color_code {text-align: center; font-weight: 700; color: blue; font-size: 16px ;}
Div. table {width: 176px; position: absolute; padding: 1px ;}
Div. tabletd {font-size: 12px; color: red; text-align: center ;}
");*/
Comparing 51js's customer service fruit script is shorter, but it may create multiple style elements, there are still some efficiency problems ...... After all, I was initially developed to edit rich texts, but the functions are not powerful!
/*
Rules for dynamically adding a style sheet
*/
ICSS = {add: function (css ){
VarD = document, $ = D. createElement ('style ');
$. SetAttribute ("type", "text/css ");
Developer.stylesheet&&().stylesheet.css Text = css) |
$. AppendChild (D. createTextNode (css ));
D. getElementsByTagName ('head') [0]. appendChild ($ );
}};
ICSS. add ("
. DhoooListBox,. dhoooListBoxli {margin: 0; padding: 0; list-style-type: none; font-size: 12px; cursor: default}
. DhoooListBox {border: 1 pxsolid # aaa; width: 180px; background: # eee; height: 200px; overflow: auto; float: left}
. DhoooListBoxli {margin: 5px; line-height: 24px; background: url (images/smilies/time.gif) no-repeat060 %; padding-left: 25px; color: #555 ;}
. DhoooListBoxli. selected {background-color: # FFCC33}
");
Finally, append several related methods:
VargetClass = function (ele ){
Returnele. className. replace (/s +/, ''). split ('');
};
VarhasClass = function (ele, cls ){
Returnele. className. match (newRegExp ('(\ s | ^)' + cls + '(\ s | $ )'));
}
VaraddClass = function (ele, cls ){
If (! This. hasClass (ele, cls) ele. className + = "" + cls;
}
VarremoveClass = function (ele, cls ){
If (hasClass (ele, cls )){
Varreg = newRegExp ('(\ s | ^)' + cls + '(\ s | $ )');
Ele. className = ele. className. replace (reg ,'');
}
}

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.