返回列表

动态引入CSS, importCssString

默认分类 2014/08/04 09:24

演示Demo:
http://haiyang.me/demo/importCssString.html
http://haiyang.me/demo/importCssString2.html
http://haiyang.me/demo/importCssString3.html

[更正]正确做法是:

<!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">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<script type="text/javascript">
<!--
function CreateStyleSheet (css) {
    // create a new style sheet 
    var style = document.createElement('style');
    var head = document.documentElement;
    head.appendChild(style);
    style.type = 'text/css';

    if (style.styleSheet){
      style.styleSheet.cssText = css;
    } 
    else {
      style.appendChild(document.createTextNode(css));
    }
}
function doit(){
    //Todo
    if ((new Date()).getTime()%1000 < 500) {
        CreateStyleSheet('body {background-color: #ff6699;}');
    }
    else {
        CreateStyleSheet('body {background-color: #00ff99;}');
    }

}

//-->
</script>
</head>

<body><button type="button" onclick="doit()">doit</button>
<style>
body {background-color: green;}
</style>

</body>

</html>

===================以下为旧的方法==================

<!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">

<head>
<script type="text/javascript">window.g = function(id){return document.getElementById(id)};</script>    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<script type="text/javascript">
<!--
function doit(id){ 
    //todo

    if (document.createStyleSheet) {
        g('out').innerHTML = 'ie';
        var styleSheetObj=document.createStyleSheet();
        styleObj=styleSheetObj.owningElement || styleSheetObj.ownerNode;
        styleObj.setAttribute('type','text/css');
        styleObj.id = id;
        styleSheetObj.addRule('button','border: 2px solid blue;');
    }
    else {
        g('out').innerHTML = 'ff';
        // create the style node, set the style
        var styleObj=document.createElement('style');
        styleObj.setAttribute('type','text/css');
        styleObj.id = id;
        styleObj.appendChild(document.createTextNode('button {border: 2px solid blue;}'));

        // append the node to the head
        var head = document.getElementsByTagName('head')[0];
        head.insertBefore(styleObj, head.firstChild);
    }
}

function doit_cancel(id) {
    var index = 0,
            sheets,
            c,
            result = false;

    if (document.createStyleSheet && (sheets = document.styleSheets)) {
        while (index < sheets.length) {
            c = sheets[index];
            if (c && c.owningElement && c.owningElement.id === id) {
                result = c.owningElement;
                break;
            }
            else if (c && c.ownerNode && c.ownerNode.id === id) {
                result = c.ownerNode;
                break;
            }
            index++;
        }
    }
    else if ((sheets = document.getElementsByTagName('style'))) {
        while (index < sheets.length) {
            c = sheets[index];
            if (c.id === id) {
                result = c;
                break;
            }
            index++;
        }
    }

    if (result) {
        c = result.parentNode;
        c.removeChild(result);
    }
}

//-->
</script>
</head>

<body>
<div id="out"></div>
<button type="button" onclick="doit('aa')">doit</button>  ddddd
<button type="button" onclick="doit_cancel('aa')">cancel</button>

</body>

</html>

修正后:

<!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">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>动态载入CSS - haiyang.me</title>
<script type="text/javascript">
<!--
window.hui = {util: {}};
    hui.util.hasCssString = function hasCssString(id, doc) {
        var sheets,
            c,
            result = false;
        doc = doc || document;
        if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
            for (var i = 0, len = sheets.length; i < len; i++) {
                c = sheets[i];
                if (c && c.owningElement && c.owningElement.id === id) {
                    result = c.owningElement;
                    break;
                }
                else if (c && c.ownerNode && c.ownerNode.id === id) {
                    result = c.ownerNode;
                    break;
                }
            }
        }
        else if ((sheets = doc.getElementsByTagName('style'))) {
            for (var i = 0, len = sheets.length; i < len; i++) {
                c = sheets[i];
                if (c.id === id) {
                    result = c;
                    break;
                }
            }
        }

        return result;
    };
    hui.util.removeCssString = function removeCssString(id, doc) {
        var parent,
            result = hui.util.hasCssString(id, doc);
        if (result) {
            parent = result.parentNode;
            parent.removeChild(result);
        }
    };

    hui.util.importCssString = function importCssString(cssText, id, doc) {
        hui.util.removeCssString(id, doc);

        doc = doc || document;
        if (doc.createStyleSheet) {
            // IE not need appendChild!
            var style = doc.createStyleSheet();
            elem = style.owningElement || style.ownerNode;
            elem.setAttribute('type', 'text/css');
            elem.id = id;
            style.cssText = cssText;
        }
        else {
            // create the style node, set the style
            var elem = doc.createElement('style');
            elem.setAttribute('type', 'text/css');
            elem.id = id;
            elem.appendChild(doc.createTextNode(cssText));

            // append the node to the head
            //var head = doc.getElementsByTagName('head')[0];
            var head = doc.documentElement;
            head.insertBefore(elem, head.lastChild);
            head.insertBefore(head.lastChild, elem);
        }

        return elem;
    };

    hui.util.addCssRule =
    hui.util.insertRule = function (className, cssText) {
        var list = document.getElementsByTagName('style'),
            styleTag = list && list.length ? list[list.length-1] : hui.util.importCssString(''),
            sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet,
            rules = sheet.cssRules || sheet.rules,
            index = rules.length,
            pre = className.indexOf('{'),
            nxt;
        if (pre !== -1) {
            nxt = className.indexOf('}', pre + 1);
            cssText = className.substring(pre + 1, nxt === -1 ? className.length : nxt);
            className = className.substring(0, pre);
        }
        // all browsers, except IE before version 9
        if (sheet.insertRule) {   
            sheet.insertRule (className + '{' + cssText + '}', index);
        }
        else {  
            // Internet Explorer before version 9
            if (sheet.addRule) {
                sheet.addRule (className, cssText, index);
            }
        }
    };



function doit() {
    /*//todo
    var div = document.createElement("hr");
    //  
    var oDiv = document.documentElement.appendChild(div);
    //var oDiv = document.documentElement.insertBefore(div, document.documentElement.lastChild);*/
    if ((new Date()).getTime()%1000 > 500) {
        //hui.util.addCssRule('div,button {color:red;}'); // Error in IE6
        //hui.util.addCssRule('button {color:red;}');
        hui.util.importCssString('div {color:red;}');
    }
    else {
        //hui.util.addCssRule('button', 'color:green;');
        hui.util.importCssString('div,button {color:green;}');
    }


}
doit();
//-->
</script>
</head>

<body><button type="button" onclick="doit()">doit</button>
<div>
123
<hr/>
456
</div>
</body>

</html>