导航栏: 首页 评论列表

IE bug 之 createStyleSheet在IE9下有次数限制,多次创建之后会出错

默认分类 2014/07/04 02:03

IE bug 之 createStyleSheet在IE9下有次数限制,多次创建之后会出错

<script type='text/javascript'>//<![CDATA[ 
window.importCssString = function importCssString(cssText, id, doc) {
    doc = doc || document;

    var style;

    if (doc.createStyleSheet) {
        style = doc.createStyleSheet();
        style.cssText = cssText;
        if (id) style.owningElement.id = id;
    } 
    else {
        style = doc.createElementNS ? doc.createElementNS('http://www.w3.org/1999/xhtml', 'style') : doc.createElement('style');

        style.appendChild(doc.createTextNode(cssText));
        if (id) style.id = id;

        doc.head.appendChild(style);
    }
};

window.doit = function doit() {
    //todo
    for (var i = 0, len = 400; i < len; i++) {
        try {
            importCssString('button {border: 1px solid green;}');
        } 
        catch (e) {
            alert(e + i);
            break;
        }

    }
}

< /script>
test 
<button type="button" onclick="doit()">doit</button>  

修改版,

hui.util.importCssString = function importCssString(cssText, id, doc) {
    doc = doc || document;
    var style = hui.util.hasCssString(id, doc);
    if (style) {
        style.parentNode.removeChild(style);
        style = null;
    }
    if (doc.createStyleSheet) {
        style = doc.createStyleSheet();
        if (id) {
            style.owningElement.id = id;
        }
        style.cssText = cssText;
    }
    else {
        style = doc.createElementNS ? doc.createElementNS('http://www.w3.org/1999/xhtml', 'style') : doc.createElement('style');
        if (id) {
            style.id = id;
        }
        style.appendChild(doc.createTextNode(cssText));
        hui.util.getDocumentHead(doc).appendChild(style);
    }
};

 


>> 留言评论