1. function addCSS(cssText){
    2. var style = document.createElement('style'), //创建一个style元素
    3. head = document.head || document.getElementsByTagName('head')[0]; //获取head元素
    4. style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
    5. if(style.styleSheet){ //IE
    6. var func = function(){
    7. try{ //防止IE中stylesheet数量超过限制而发生错误
    8. style.styleSheet.cssText = cssText;
    9. }catch(e){
    10. }
    11. }
    12. //如果当前styleSheet还不能用,则放到异步中则行
    13. if(style.styleSheet.disabled){
    14. setTimeout(func,10);
    15. }else{
    16. func();
    17. }
    18. }else{ //w3c
    19. //w3c浏览器中只要创建文本节点插入到style元素中就行了
    20. var textNode = document.createTextNode(cssText);
    21. style.appendChild(textNode);
    22. }
    23. head.appendChild(style); //把创建的style元素插入到head中
    24. }
    25. //使用
    26. addCSS('#demo{ height: 30px; background:#f00;}');