CSS——创建css

        CreateInlineStyle: function () {   //创建一个内联样式表
            var style = document.createElement('style'); //创建一个style元素
            var head = document.head || document.getElementsByTagName('head')[0]; //获取head元素
            style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
            head.appendChild(style); //把创建的style元素插入到head中    
            return style;
        },
        GetInlineStyle: function () {   //获取一个内联样式表; 从后往前搜索
            var head = document.head || document.getElementsByTagName('head')[0]; //获取head元素
            var children=head.children;
            var inlineStyle = null;
            for (var i = children.length - 1; i >= 0; i--) {
                var node = children[i];
                if (node.tagName == "STYLE" && node.type == "text/css") {
                    inlineStyle = node;
                    break;
                }
            }
            if (!inlineStyle) {  //不存在内联式的样式表则创建
                inlineStyle = this.CreateInlineStyle();
            }

            return inlineStyle;
        },
        AddInlineCSS: function (cssText) {
            var style = this.GetInlineStyle();
            if (style.styleSheet) { //IE
                var func = function () {
                    try { //防止IE中stylesheet数量超过限制而发生错误
                        style.styleSheet.cssText = cssText;
                    } catch (e) {
                        console.log("stylesheet数量超过限制!");
                    }
                }
                //如果当前styleSheet还不能用,则放到异步中则行
                if (style.styleSheet.disabled) {
                    setTimeout(func, 10);
                } else {
                    func();
                }
            } else { //w3c
                //w3c浏览器中只要创建文本节点插入到style元素中就行了
                var textNode = document.createTextNode(cssText);
                style.appendChild(textNode);
            }
        }

使用:

var cssRowAltBackColor = cssSelect + " tr.datagrid-row-alt{ background-color:" + customStyle.rowAltBackColor + "}";
BA.AddInlineCSS(cssRowAltBackColor);

posted @ 2016-08-10 18:52  志在天涯  阅读(260)  评论(0编辑  收藏  举报