使用javascript创建一个createStyleSheet函数(终极解决方案?)

时间:2013-12-11 14:10:20

标签: javascript css

我读过this link,其中Cristoph创建了一个添加样式表的功能。我认为这是一个绝妙的主意,但不能正常工作。例如:

if(typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if(typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if(typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if(typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if(typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

document.createStyleSheet( 'css/test.css' );
var sheet = document.createStyleSheet();
sheet.addRule('h1', 'background: red;');
console.log( sheet );

当我添加外部文件然后添加没有名称的样式表时,该功能至少在chrome中无法正常工作。在工作表变量中存储了一个默认的chrome样式表:

CSSStyleSheet {rules: CSSRuleList, cssRules: CSSRuleList, ownerRule: null, media: MediaList, title: null…}
cssRules: CSSRuleList
0: CSSStyleRule
1: CSSStyleRule
2: CSSStyleRule
3: CSSStyleRule
...
627: CSSStyleRule
628: CSSStyleRule
length: 629
__proto__: CSSRuleList
disabled: false
href: null
media: MediaList
ownerNode: style
ownerRule: null
parentStyleSheet: null
rules: CSSRuleList
title: null
type: "text/css"
__proto__: CSSStyleSheet

我不知道为什么会出现这个问题。有谁知道吗?

编辑:澄清源代码的概念。

谢谢!

0 个答案:

没有答案