give the function first.
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];} The 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 transparent filter var T = csscode of IE. 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;} else if (Doc. getboxobjectfor) {styleelement. innerhtml + = csscode; // Firefox supports adding style sheet strings directly to 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 CSSCodeWe can call the style method, as shown in figure
VaR DDD = Document. getelementbyid ("DDD"); DDD. style. Border = "1px solid red ";
It doesn't matter if it is longer:
VaR DDD = Document. getelementbyid ("DDD" contains invalid ddd.style.css text = "border: 1px solid red; 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 example
Function addsheetfile (PATH) {var fileref = document. createelement ("Link") fileref. rel = "stylesheet"; fileref. type = "text/CSS"; fileref. href = path; fileref. media = "screen"; var headobj = 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.
VaR ostylesheet = 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:
VaR IFRAME = Document. createelement ('iframe'); // generate the Rich Text Editor var iframedocument = 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.
the problem is that the stylesheet element is dynamically generated and the CSS string is added 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 as:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml" XML: lang = "en" lang = "en">
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.
VaR styleelement = styleelements [0]; var media = 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, Submit to the projector;
- Aural, Speaker;
- Braille, Submitted to the convex-click 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.
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. table TD {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!
/* Dynamically Add a style sheet Rule */ICSS = {Add: function (CSS) {var d = Document, $ = D. createelement ('style'); $. setattribute ("type", "text/CSS" example }}.stylesheet&&().stylesheet.css text = CSS) | $. appendchild (D. createtextnode (CSS); D. getelementsbytagname ('head') [0]. appendchild ($) ;}}; ICSS. add ("\. dhooolistbox ,. dhooolistbox Li {margin: 0; padding: 0; List-style-type: none; font-size: 12px; cursor: Default }\. dhooolistbox {border: 1px solid # AAA; width: 180px; Background: # Eee; Height: 200px; overflow: auto; float: Left }\. dhooolistbox Li {margin: 5px; line-Height: 24px; Background: URL (images/smilies/time.gif) No-repeat 0 60%; padding-left: 25px; color: #555 ;}\. dhooolistbox Li. selected {background-color: # ffcc33 }\");
Finally, append several related methods:
var getclass = function (Ele) {return ELE. classname. replace (/\ s + /,''). split ('') ;}; var hasclass = function (Ele, CLS) {return ELE. classname. match (New Regexp ('(\ s | ^)' + CLS + '(\ s | $ )'));} // faster version var hasclass = function (Ele, CLS) {return-1 <("" + ELE. classname + ""). indexof ("" + CLS + "");} var addclass = function (Ele, CLS) {If (! This. hasclass (Ele, CLS) ELE. classname + = "" + CLS;} var removeclass = function (Ele, CLS) {If (hasclass (Ele, CLS )) {var Reg = new Regexp ('(\ s | ^)' + CLS + '(\ s | $)'); ELE. classname = ELE. classname. replace (Reg, '') ;}