小编典典

导出DOM元素的CSS

css

我经常在网上找到漂亮的样式。要复制DOM元素的CSS,我使用Google
Chrome开发者工具检查该元素,查看各种CSS属性,然后将其手动复制到我自己的样式表中。

是否可以轻松导出给定DOM元素的所有CSS属性?


阅读 595

收藏
2020-05-16

共1个答案

小编典典

这是一种exportStyles()方法的代码,该方法应返回一个CSS字符串,包括给定元素的所有内联和外部样式,默认值 除外 (这是主要困难)。

例如: console.log(someElement.exportStyles());

由于您使用的是Chrome,因此我无需理会它与IE兼容。实际上,只需要浏览器支持该getComputedStyle(element)方法即可。

Element.prototype.exportStyles = (function () {

    // Mapping between tag names and css default values lookup tables. This allows to exclude default values in the result.
    var defaultStylesByTagName = {};

    // Styles inherited from style sheets will not be rendered for elements with these tag names
    var noStyleTags = {"BASE":true,"HEAD":true,"HTML":true,"META":true,"NOFRAME":true,"NOSCRIPT":true,"PARAM":true,"SCRIPT":true,"STYLE":true,"TITLE":true};

    // This list determines which css default values lookup tables are precomputed at load time
    // Lookup tables for other tag names will be automatically built at runtime if needed
    var tagNames = ["A","ABBR","ADDRESS","AREA","ARTICLE","ASIDE","AUDIO","B","BASE","BDI","BDO","BLOCKQUOTE","BODY","BR","BUTTON","CANVAS","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","COMMAND","DATALIST","DD","DEL","DETAILS","DFN","DIV","DL","DT","EM","EMBED","FIELDSET","FIGCAPTION","FIGURE","FONT","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEAD","HEADER","HGROUP","HR","HTML","I","IFRAME","IMG","INPUT","INS","KBD","KEYGEN","LABEL","LEGEND","LI","LINK","MAP","MARK","MATH","MENU","META","METER","NAV","NOBR","NOSCRIPT","OBJECT","OL","OPTION","OPTGROUP","OUTPUT","P","PARAM","PRE","PROGRESS","Q","RP","RT","RUBY","S","SAMP","SCRIPT","SECTION","SELECT","SMALL","SOURCE","SPAN","STRONG","STYLE","SUB","SUMMARY","SUP","SVG","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TIME","TITLE","TR","TRACK","U","UL","VAR","VIDEO","WBR"];

    // Precompute the lookup tables.
    for (var i = 0; i < tagNames.length; i++) {
        if(!noStyleTags[tagNames[i]]) {
            defaultStylesByTagName[tagNames[i]] = computeDefaultStyleByTagName(tagNames[i]);
        }
    }

    function computeDefaultStyleByTagName(tagName) {
        var defaultStyle = {};
        var element = document.body.appendChild(document.createElement(tagName));
        var computedStyle = getComputedStyle(element);
        for (var i = 0; i < computedStyle.length; i++) {
            defaultStyle[computedStyle[i]] = computedStyle[computedStyle[i]];
        }
        document.body.removeChild(element); 
        return defaultStyle;
    }

    function getDefaultStyleByTagName(tagName) {
        tagName = tagName.toUpperCase();
        if (!defaultStylesByTagName[tagName]) {
            defaultStylesByTagName[tagName] = computeDefaultStyleByTagName(tagName);
        }
        return defaultStylesByTagName[tagName];
    }

    return function exportStyles() {
        if (this.nodeType !== Node.ELEMENT_NODE) {
            throw new TypeError("The exportStyles method only works on elements, not on " + this.nodeType + " nodes.");
        }
        if (noStyleTags[this.tagName]) {
            throw new TypeError("The exportStyles method does not work on " + this.tagName + " elements.");
        }
        var styles = {};
        var computedStyle = getComputedStyle(this);
        var defaultStyle = getDefaultStyleByTagName(this.tagName);
        for (var i = 0; i < computedStyle.length; i++) {
            var cssPropName = computedStyle[i];
            if (computedStyle[cssPropName] !== defaultStyle[cssPropName]) {
                styles[cssPropName] = computedStyle[cssPropName];
            }
        }

        var a = ["{"];
        for(var i in styles) {
            a[a.length] = i + ": " + styles[i] + ";";
        }
        a[a.length] = "}"
        return a.join("\r\n");
    }

})();
2020-05-16