使用Javascript将CSS标记输出到字符串

Output CSS Markup to a string using Javascript

本文关键字:输出 字符串 Javascript CSS 使用      更新时间:2023-09-26

我想知道是否有人有过使用javascript输出给定元素的css标记的经验。

注意:仅使用Webkit。

例如:

HTML:

<div id="css"></div>

样式:

#css {
    background: #F1F3F5;
    border: 1px solid #B4BFC9;
    -moz-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
}

漂亮的jQuery插件?:(

alert($('#css').getCSS());

警报

#css {
    background: #F1F3F5;
    border: 1px solid #B4BFC9;
    -moz-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
}
function css(a){
    var sheets = document.styleSheets, o = {};
    for(var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for(var r in rules) {
            if(a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}
function css2json(css){
        var s = {};
        if(!css) return s;
        if(css instanceof CSSStyleDeclaration) {
            for(var i in css) {
                if((css[i]).toLowerCase) {
                    s[(css[i]).toLowerCase()] = (css[css[i]]);
                }
            }
        } else if(typeof css == "string") {
            css = css.split("; ");          
            for (var i in css) {
                var l = css[i].split(": ");
                s[l[0].toLowerCase()] = (l[1]);
            };
        }
        return s;
    }

用法:

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);