There is no doubt that based on the principle of separation of performance and structure, directly importing a new style sheet is the best choice, but in some cases it will not work. For example, if we make a draggable DIV, from the perspective of setting styles, it is Position it absolutely to prevent it from affecting the original document flow, and then change its top and left values little by little to achieve the effect of movement. Since dragging has a time concept, 24 frames per second, it is impossible to include everything in the style sheet. Therefore, it is very 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 have been expanded.
Taking a step back, the separation of performance and structure is not limited to importing style sheets. You know, there are three types of styles, external styles, internal styles, and inline styles.
* External style, the one we mentioned above, is written in a separate CSS file.
* Internal style is written independently in a style tag, usually placed in the head tag. The style generated by the last function I provided is the internal style.
* Inline style is the style written in the style attribute of the element.
The newly added interfaces are mainly concentrated in external styles - I say interfaces because the corresponding implementations are provided by the browser. Arrogant guys like IE6 never ignore their existence.
In the W3C model, the link tag and style tag of type "text/css" both represent a CSSStyleSheet object. We can obtain all CSSStyleSheet objects in the current page through document.styleSheets, but this is A collection, not a simple array. Each CSSStyleSheet object has the following properties,
* type: always returns "text/css" string.
* disabled: has the same effect as input's disabled, and the default is false.
* href: Returns the URL, if the style tag is null.
* title: Returns the value of its title. The title is the same as the title of an ordinary element. You can write whatever you like.
* media: The things returned by IE and Firefox are not consistent, so it’s hard to say. media is used to specify which devices the style rules it owns are valid for. The default is all.
* ownerRule: Returns a read-only CSSRule object if the style sheet is introduced with @import.
* cssRules: Returns a collection of read-only style rule objects (CSSStyleRule objects).
The CSSStyleRule object is created by W3C in order to set the style in more detail. For example, the following thing corresponds to a style rule object:
button[type] {
padding:4px 10px 4px 7px;
line-height :17px;
}
The style rule object has the following main attributes: type, cssText, parentStyleSheet, parentRule.
type is somewhat similar to nodeType, which subdivides style rules. It uses 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 (define a CSSCharsetRule object for setting the current The character set of the style sheet is the same as the current web page by default)
* 3: CSSRule.IMPORT_RULE (define a CSSImportRule object, which is to use @import to introduce other style sheets)
* 4: CSSRule.MEDIA_RULE (define a CSSMediaRule Object, used to set whether this style is used for monitors, printers, projectors, etc.)
* 5: CSSRule.FONT_FACE_RULE (define a CSSFontFaceRule object, @font-face of CSS3)
* 6: CSSRule. PAGE_RULE (define a CSSPageRule object)
Needless to say, cssText is a very useful attribute that directly converts strings into style rules, ignoring the differences in style attributes of each browser, such as cssFloat and styleFloat.
parentStyleSheet and parentRule are both for @import. However, @import has problems under IE, so I basically don’t use it.
There are a few unexpected methods:
* nsertRule(rule,index): Add a style rule.
* deleteRule(index): Remove a style rule.
* getPropertyValue(propertyName) Gets the value of the corresponding style attribute of the element. If we obtain a style rule object, we can use CSSStyleRuleObject.getPropertyValue("color") to obtain its font color setting. Compared with the ordinary el.style.color method, its efficiency is quite high, because el.style.color obtains the inline style. Freaks like IE cannot get it at all if your element does not set the style attribute. The prepared value may be empty, it may be inherit... there may be compatibility issues, and this inline attribute is not necessarily the style ultimately applied to the element. IE can only call the less useless el.currentStyle[prop], other browsers The processor calls document.defaultView.getComputedStyle(el, "")[prop] which is quite impressive but a bit cumbersome.
* removeProperty(propertyName) removes the corresponding style attribute of the element.
* setProperty(propertyName, value, priority) sets the element to add a style and also specifies the priority.
We can get a function to set the style:
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 a hyphen style, el.style.setProperty('background-color','red',null);
el.style.setProperty(hyphenize(property),styles[property] ,null);
} else {
//Must be camel case 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'
});
But I don’t like this method very much. It generates inline styles, and it has to deal with float and opacity. In the inline style of IE7, there is a bug in the filter. You must let it get hasLayout, otherwise the filter will not take effect (we can check its status through el.currentStyle.hasLayout). Therefore, instead of setting them one by one, it is better to use cssText to catch them all.
Finally, I attach my enhanced version of the addSheet method. It adds the function of automatically processing opacity, which means that we only need to set the cssText according to the standard, and it will automatically generate the corresponding filter. This will at least allow browsers such as Firefox to pass the W3C inspection.
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 has the most Accepts two parameters!");
}
if(! "v1"){//New function, users only need to enter the W3C transparent style, and it will automatically convert into IE's 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 a newline character at the end to facilitate firebug Check.
var headElement = doc.getElementsByTagName("head")[0];
var styleElements = headElement.getElementsByTagName("style");
if(styleElements.length == 0){//if not If the style element exists, 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 new internal style
}else if(doc.getBoxObjectFor) {
styleElement.innerHTML = cssCode;//Firefox supports adding style sheet strings directly to innerHTML
}else{
styleElement.appendChild(doc.createTextNode(cssCode))
}
}