styleSheet 操作类

除了IE,跨域的 css 文件的 cssRules 是无法读出的,

在 chrome 中,link 引入的 css 文件即使不跨域,网页文件也需要使用 url 的方式打开才能读取 cssRules

所以,下面这个想法仅局限于 IE 9  以上,非跨域环境

.xxx { content:'CSSRequire: selector1|selector2|selector3' }

果如想在服务器端使用脚本合成 css 样式文件,记得为 link 加上属性rel="stylesheet",否则不生效:

<link rel="stylesheet" href="cssMerge.php?file=main" />

输出 css 代码的文件注意设置content-type ,否则 IE9 拒绝解析

header("content-type:text/css");  //php

var StyleSheetOperator = (function(){ // by ecalf
    var f = function(index){
        this.constructor = arguments.callee;
        this.styleSheet = null;        
        this.init(index);
    };
    f.prototype={
        init:function(index){
            var host = this;
            host.styleSheet = host.selectSheet(index);
            return host; 
        },
        isCrossSite:function(sheet){//是否为跨域css文件
            var host = this;
            sheet = sheet||host.styleSheet;
            if(sheet.href){//link css file
                var reg1 = new RegExp('^https?://','i');
                if(reg1.test(sheet.href)){
                    var reg2 = new RegExp('^https?://'+window.location.host+'/','i');
                    return !reg2.test(sheet.href);
                }
            }
            return false;
        },
        createStyleSheet:function(cssText){
            var host = this;
            var styleSheet = null;
            cssText = cssText||"";
 
            if(document.createStyleSheet){//ie
                styleSheet = document.createStyleSheet();
                styleSheet.cssText = cssText;
            }else{
                var styleSheets = document.styleSheets;
                var styleNode = document.createElement("style");
                styleNode.innerHTML = cssText; 
                var head = document.getElementsByTagName("head");
                if(head.length){
                    head[0].appendChild(styleNode);
                }else{
                    document.body.appendChild(styleNode);
                }
 
                styleSheet = styleSheets[styleSheets.length-1];
            }
 
            return styleSheet;
        },
 
        getSheet:function(index){
            var host = this;
            var styleSheets = document.styleSheets;
            if(!styleSheets.length){
                return  null;
            }else if(index==undefined){
                index = styleSheets.length-1;
            }else{
                index = host.numberInRange(0,index||0,styleSheets.length-1);
            }
                        
            return styleSheets[index];
        },

        selectSheet:function(index){
            var host = this;            
            host.styleSheet = host.getSheet(index);

            return host.styleSheet;
        },
 
        getRules:function(){
            var host = this;
            return host.styleSheet.cssRules||host.styleSheet.rules;
        },
 
        getRule:function(index){
            var host = this;
            var rules = host.getRules();
            index = host.numberInRange(0,index||0,rules.length-1);
            return rules[index];
        },
 
        insertRule:function(selector,cssText,index){
            var host = this;
            var selectorCssText;
            if(arguments.length==1||!isNaN(arguments[1]*1)){ 
                index = arguments[1]*1;
                selectorCssText = selector;
                selector = selectorCssText.match(/^.+(?=\{)/)[0];
                cssText = selectorCssText.match(/\{.+\}/)[0];                                            
            }else{
                selectorCssText = selector+'{'+cssText+'}';
                index = arguments[2]*1;
            }
            if(isNaN(index)){
                index = host.getRules().length;
            }else if(index<0){
                index = 0
            }
             
            //console.log(selector,cssText,selectorCssText,index); 
              
            if(host.styleSheet.insertRule){       
                host.styleSheet.insertRule(selectorCssText,index);
            }else{
                host.styleSheet.addRule(selector,cssText,index);
            }
 
 
            return host;
        },
 
        deleteRule:function(index){
            var host = this;
            var rulesCount = host.getRules().length;
            index = index*1||0;
            if(index>=0&&index<=rulesCount-1){
                if(host.styleSheet.deleteRule){
                    host.styleSheet.deleteRule(index);
                }else{
                    host.styleSheet.removeRule(index);
                }
            }
 
            return host;
        },
 
        getRulesBySelector:function(selector){
            var host = this;
            var rules = host.getRules();
            var fetchRules = [];
            selector = selector.replace(/^\s+|\s+$/g,'').toLowerCase();
            for(var i=0,l=rules.length;i<l;i++){
                if(rules[i].selectorText.toLowerCase()==selector){
                    fetchRules.push(rules[i]);
                }
            }
 
            return fetchRules.length?fetchRules:null;
        },
 
        deleteRuleBySelector:function(selector){
            var host = this;
            var rules = host.getRules();
            selector = selector.replace(/^\s+|\s+$/g,'').toLowerCase();
            for(var i=0,l=rules.length;i<l;i++){
                if(rules[i].selectorText.toLowerCase()==selector){
                    host.deleteRule(i);
                    i-=2;
                }
            }
 
            return host;
        },
 
        getCssText:function(){
            var host = this;
            var cssText='';
            if(host.styleSheet.cssText){
                cssText = host.styleSheet.cssText;
            }else{
                var rules = host.getRules();
                for(var i=0,l=rules.length;i<l;i++){
                    cssText += rules[i].cssText;
                }
            }
 
            return cssText;
        },
 
        addCssText:function(cssText){
            var host = this;
            if(host.styleSheet.cssText){
                host.styleSheet.cssText +=";"+cssText;
            }else{
                var cssRules = host.cssStrToRules(cssText);
                var rulesCount = host.getRules().length;
                for(var i=0,l=cssRules.length;i<l;i++){
                    host.insertRule(cssRules[i],rulesCount+i);
                }
            }
 
            return host;
        },
 
        setCssText:function(cssText){
            var host = this;
            if(host.styleSheet.cssText){
                host.styleSheet.cssText = cssText;
            }else{
                var currentRules = host.getRules();
                while(currentRules.length){//clear old cssRules
                    host.deleteRule(0);
                }
 
                var cssRules = host.cssStrToRules(cssText);
                for(var i=0,l=cssRules.length;i<l;i++){
                    host.insertRule(cssRules[i],i);
                }
            }
 
            return host;
        },
 
        cssStrToRules:function(cssText){
            return cssText.replace(/^\s+|\s+$/g,'')
                        .replace(/\}(?=(?:.+\{.+\}))/g,'}\0\0\0') //give a mark
                        .split(/\0{3}\s*/);
        },
 
        setDisabled:function(frag){
            var host = this;
            host.styleSheet.disabled = !!frag;
            return host;
        },
     
        numberInRange:function(min,max,n){
            return [min,n,max].sort(function(a,b){return a-b;})[1];
        }
 
    };
 
    return f;
})();
原文地址:https://www.cnblogs.com/ecalf/p/css_style_class.html