动态添加样式(转载)

function addCSS(content) {
        $('<style type="text/css">' + content + '</style>').appendTo("head");
    }
    $(function() {
        addCSS("body { background-color: #ccc; }");
    });


var ss1 = document.createElement('style');
    var def = 'body {color: red;}';
    ss1.setAttribute("type", "text/css");
    if (ss1.styleSheet) {   // IE
        ss1.styleSheet.cssText = def;
    } else {                // the world
        var tt1 = document.createTextNode(def);
        ss1.appendChild(tt1);
    }
    var hh1 = document.getElementsByTagName('head')[0];
    hh1.appendChild(ss1);

function addCSS2(content) {
        var div = document.createElement("div");
        div.innerHTML = '&nbsp;<style type="text/css">' + content + '</style>';
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(div);
        // 删除style外面的div标签
        head.replaceChild(div.getElementsByTagName("style")[0], div);
    }
    $(function() {
        addCSS2("body { background-color: #ccc; }");
    });

转自:http://www.cnblogs.com/sanshi/archive/2009/08/06/1540197.html
   

原文地址:https://www.cnblogs.com/johnwonder/p/1742006.html