开发者

Create CSS with jQuery (prependTo & append) will not work for Internet Explorer

i want to create a large CSS and it works fine in Firefox and Crome, but I开发者_高级运维nternet Explorer don't unterstand my jQuery script. Any ideas how to solve this problem?

$("<style>")
    .attr("type","text/css")
    .prependTo("head")
    .append("h1 {color: #F00}")
    .append("h2 {color: #0F0}")
    .append("h3 {color: #00F}")


Use this code to add css rules dynamically (tested on majority of browsers):

function dyn_css_rule(sSelector, sCssText) {
    try {
        var aSS = document.styleSheets;
        var i;
        for (i=aSS.length-1; i>=0; i--) {
            var oCss = document.styleSheets[i];
            var sMedia = (typeof(oCss.media) == "string")?
                oCss.media:
                oCss.media.mediaText;
            if (!sMedia
                || sMedia.indexOf("screen") != -1
                || sMedia.indexOf("all") != -1
            ) {
                break;
            }
        }
        if (oCss.insertRule) {
            oCss.insertRule(sSelector + " {" + sCssText + "}", oCss.cssRules.length);
        } else if (oCss.addRule) {
            oCss.addRule(sSelector, sCssText);
        }
    } catch(err) {
        var tag = document.createElement('style');
        tag.type = 'text/css'; 
        try {
            tag.innerHTML = sSelector + " {" + sCssText + "}";
        } catch(err) {
            tag.innerText = sSelector + " {" + sCssText + "}";
        }
        document.getElementsByTagName('head')[0].appendChild(tag);
    }
    return sSelector + "{" + sCssText + "}";
};

Usage:

dyn_css_rule("h1", "color: #F00");


Try $("<style></style>"). IE doesn't like the single version.

$("<style></style>").attr("type","text/css")
    .prependTo("head")
    .append("h1 {color: #F00}")
    .append("h2 {color: #0F0}")
    .append("h3 {color: #00F}");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜