JS function to implement dynamic add CSS style sheet file _ basics

Source: Internet
Author: User
Give the function first.
Copy Code code 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 accepts up to two arguments!");
}
if (!+ "v1") {//increase the automatic conversion transparency feature, the user only needs to enter the transparent style of the consortium, it will automatically convert to 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 under Firebug.
Varheadelement=doc.getelementsbytagname ("Head") [0];
Varstyleelements=headelement.getelementsbytagname ("style");
if (styleelements.length==0) {//If no style element exists then 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.csstext+=csscode;
}elseif (doc.getboxobjectfor) {
styleelement.innerhtml+=csscode;//Firefox support direct InnerHTML add a style table string
}else{
Styleelement.appendchild (Doc.createtextnode (Csscode))
}
}

Sometimes we need to introduce some CSS styles to the document dynamically in the. js file. For some short CSS code, this is good, we can call its style method, such as
Copy Code code as follows:

Varddd=document.getelementbyid ("ddd");
Ddd.style.border= "1pxsolidred";

It doesn't matter if it's a little longer:
Copy Code code as follows:

Varddd=document.getelementbyid ("ddd");
ddd.style.csstext= "Border:1pxsolidred;color: #000; background: #444; Float:left";

Personally, I like the latter. Because the former has a serious compatibility problem. such as float this style, in IE is stylefloat, in Firefox, such as the standard browser is cssfloat. And Csstext is a winner.
If it is very long, we can dynamically import a CSS file. Such as
Copy Code code as follows:

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 bit cumbersome in IE. I have always supported which browser to use the native function of which browser, the direct use of binary code is the most efficient.
Copy Code code as follows:

Varostylesheet=document.createstylesheet (Surl,iindex);

The two parameters of the createStyleSheet band are optional.
But if our style is unique to a particular page, and only administrators can use it, and that part of the page is dynamically generated, do we need to introduce it from the start? Do you need to get a file to load it specifically? The best way to get these styles bundled with dynamic scripts. My function is developed for this purpose.
Frankly, it was first developed for rich-text editors. As you all know, the most popular way of rich text input is to put the content into the IFRAME, which involves two kinds of documents, one page document and the other is the document of IFRAME. The document of IFrame also involves compatibility issues. We can:
Variframe=document.createelement (' iframe ');//Generate Richtexteditor for editing
variframedocument=iframe.contentdocument| | Iframe.contentWindow.document;
......
Well, it's a long way off. In short, the first judgment of the function is to prepare for both of these document. If the IFRAME is not involved, we can just pass in one parameter. The last argument is always a CSS string.
Then there is the problem of dynamically generating stylesheet elements and adding CSS strings to this element. Of course, if there is a current stage, of course, use ready-made. The more DOM elements, the greater the burden on the viewer. We think of document.stylesheets method. It returns a collection that contains a STYLE element and a link element, as well as a compatibility issue, such as:
Copy Code code as follows:

<! Doctypehtmlpublic "-//w3c//dtdxhtml1.0transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<metahttp-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<% #强制IE8像IE7一样呈现网页-%>
<metahttp-equiv= "x-ua-compatible" content= "ie=emulateie7″/>
<%#--Default all links are open in this window-%>
<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>

Above with alert (document.styleSheets.length); test, ie return to 6,W3C browser return 5. Therefore, it was rejected. And we use only the style element, not the outer-union. The second part of the decision on the head of the style element, did not create one. Then we add the CSS string to the first STYLE element.
Then we have to add the lock, because when media= "print", only when the page is printed, the effect of the definition is valid. To prevent the media value of the first STYLE element from being screen, we have to change it.
Copy Code code as follows:

Varstyleelement=styleelements[0];
Varmedia=styleelement.getattribute ("Media");
if (Media!=null&&!/screen/.test (Media.tolowercase ())) {
Styleelement.setattribute ("Media", "screen");
}

Attach some instructions for media.
Screen (default), submitted to computer screens;
Print, output to printer;
Projection, submitted to the projector;
Aural, loudspeaker;
Braille, submitted to Braille tactile sensing device;
TTY, telex (using fixed fonts);
TV, TV;
All, output devices.
Finally, the question is added. Divided into IE, Firefox and other three kinds of browser. The decision viewer also uses individual private properties or methods. If stylesheet is used exclusively by IE, Getboxobjectfor is used by Firefox alone (you can also use it (/firefox/.test (navigator.userAgent.toLowerCase)), Dom operations are usually the most time-consuming, private use of private!
Use the method.
Copy Code code 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;}
");*/
Compared to the 51JS customer service fruit script, shorter, but it will probably create multiple style elements, there are some efficiency problems ... After all, I was originally developed for the development of rich text editing, the function is not powerful AH!
/*
Rules for dynamically adding style sheets
*/
Icss={add:function (CSS) {
Vard=document,$=d.createelement (' style ');
$.setattribute ("type", "text/css");
$.stylesheet&& ($.STYLESHEET.CSSTEXT=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:1pxsolid#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%;p adding-left : 25px;color: #555;}
. Dhooolistboxli.selected{background-color: #FFCC33}
");
Finally, add a few 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.