jQuery - 如何使用元素的HTML获取所有样式/ css(在内部/外部文档中定义)

时间:2011-01-24 11:26:59

标签: javascript jquery css styles

我知道$("#divId").html()会给我innerHtml。我还需要它的样式(可以通过类的方式定义)内联style属性或单独的<style>标记内的所有样式/类。

有可能吗?

UPDATE
如果html与<div id="testDiv">cfwcvb</div>类似,并且#testDiv的css类在外部样式表中定义,该怎么办?

更新2
很抱歉没有澄清这个

如果这是我的HTML

<div id="divId">
    <span class="someClass">Some innerText</span>
</div>

样式在单独的样式表或头部样式中定义。

#divId {
    clear: both;
    padding: 3px;
    border: 2px dotted #CCC;
    font-size: 107%;
    line-height: 130%;
    width: 660px;
}
.someClass {
    color: blue;
}

然后,当我尝试获取$("#divId").html()的内部html或调用任何其他自定义函数时,我需要类似下面的内容

<style>
#divId {
    clear: both;
    padding: 3px;
    border: 2px dotted #CCC;
    font-size: 107%;
    line-height: 130%;
    width: 660px;
}
.someClass {
    color: blue;
}
</style>

<div id="divId">
    <span class="someClass">Some innerText</span>
</div>

通过kirilloid 回复更新3 我在this页面本身的Chrome调试器工具的命令窗口中运行了以下代码,这就是我看到的TypeError: Cannot read property 'rules' of undefined

function getElementChildrenAndStyles(selector) {
  var html = $(selector).get(0).outerHTML;

  selector = selector.split(",").map(function(subselector){
    return subselector + "," + subselector + " *";
  }).join(",");
  elts = $(selector);

  var rulesUsed = [];
  // main part: walking through all declared style rules
  // and checking, whether it is applied to some element
  sheets = document.styleSheets;
  for(var c = 0; c < sheets.length; c++) {
    var rules = sheets[i].rules || sheets[i].cssRules;
    for(var r = 0; r < rules.length; r++) {
      var selectorText = rules[r].selectorText;
      var matchedElts = $(selectorText);
      for (var i = 0; i < elts.length; i++) {
        if (matchedElts.index(elts[i]) != -1) {
          rulesUsed.push(CSSrule); break;
        }
      }
    }
  }
  var style = rulesUsed.map(function(cssRule){
    if ($.browser.msie) {
      var cssText = cssRule.style.cssText.toLowerCase();
    } else {
      var cssText = cssRule.cssText;
    }
    // some beautifying of css
    return cssText.replace(/(\{|;)\s+/g, "\$1\n  ").replace(/\A\s+}/, "}");
    //                 set indent for css here ^ 
  }).join("\n");
  return "<style>\n" + style + "\n</style>\n\n" + html;
};
getElementChildrenAndStyles(".post-text:first");

9 个答案:

答案 0 :(得分:12)

outerHTML(不确定,你需要它 - 以防万一)

限制:使用CSSOM,样式表应来自同一个来源。

function getElementChildrenAndStyles(selector) {
  var html = $(selector).outerHTML();

  selector = selector.split(",").map(function(subselector){
    return subselector + "," + subselector + " *";
  }).join(",");
  elts = $(selector);

  var rulesUsed = [];
  // main part: walking through all declared style rules
  // and checking, whether it is applied to some element
  sheets = document.styleSheets;
  for(var c = 0; c < sheets.length; c++) {
    var rules = sheets[c].rules || sheets[c].cssRules;
    for(var r = 0; r < rules.length; r++) {
      var selectorText = rules[r].selectorText;
      var matchedElts = $(selectorText);
      for (var i = 0; i < elts.length; i++) {
        if (matchedElts.index(elts[i]) != -1) {
          rulesUsed.push(rules[r]); break;
        }
      }
    }
  }
  var style = rulesUsed.map(function(cssRule){
    if (cssRule.style) {
      var cssText = cssRule.style.cssText.toLowerCase();
    } else {
      var cssText = cssRule.cssText;
    }
    // some beautifying of css
    return cssText.replace(/(\{|;)\s+/g, "\$1\n  ").replace(/\A\s+}/, "}");
    //                 set indent for css here ^ 
  }).join("\n");
  return "<style>\n" + style + "\n</style>\n\n" + html;
}

用法:

getElementChildrenAndStyles("#divId");

答案 1 :(得分:8)

没有jQuery,没有IE支持,这就是我所能做的:

enter image description here

<!doctype html>

<html>
    <head>
        <meta charset = "utf-8">

        <script type = "text/javascript">
            Element.prototype.getStyles = function () {
                var array = {};
                var styles = window.getComputedStyle (this, null);

                for (var i = 0; i < styles.length; i ++) {
                    var style = styles[i];

                    array[style] = styles[style];
                }

                return array; // return new Array (array, this.innerHTML); You can also return the HTMl content. I don't think its necessary
            }

            window.addEventListener ("load", function () {
                var divId = document.getElementById ("divId");
                var someClass = document.getElementsByClassName ("someClass");

                var string = "";
                var styles = divId.getStyles ();

                for (var i in styles) {
                    string += i + ": " + styles[i] + "\n";
                }

                alert (string);
                alert ("In-line style: Height ->" + styles["height"] + "\n" + "Out-line style: Width ->" + styles["width"])
                alert ("HTML: " + divId.innerHTML);

                // Same thing with the span element
            }, false);
        </script>

        <style>
            #divId {
                clear: both;
                padding: 3px;
                border: 2px dotted #CCC;
                font-size: 107%;
                line-height: 130%;
                width: 660px;
            }
            .someClass {
                color: blue;
            }
        </style>

        <title>Test</title>
    </head>

    <body>
        <div id = "divId" style = "height: 100px">
            <span class = "someClass">Some innerText</span>
        </div>
    </body>
</html>

答案 2 :(得分:6)

您可以在大多数浏览器中使用window.getComputedStyle()和IE中元素的currentStyle属性来获取表示元素计算样式的样式对象。但是,有几种浏览器差异,其中为快捷方式属性(例如background),颜色RGB值,长度甚至font-weight返回了值(请参阅this useful test page)。仔细测试。

function computedStyle(el) {
    return el.currentStyle || window.getComputedStyle(el, null);
}

alert(computedStyle(document.body).color);

答案 3 :(得分:4)

你可以在脚本中使用这样的东西: -

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function(){
    var styleVal = $('#testDiv').attr('style');
    console.warn("styleVal >>>   " + styleVal);
})
</script>

和简单的html就像这样

<div style="border:1px solid red;" id="testDiv">cfwcvb</div>

答案 4 :(得分:3)

如果你想保存一个元素的所有风格,我认为这会比你想象的更复杂 首先,我的第一个ide是firebug css控制台。这显示了所有元素的风格,我想怎么样? 所以我搜索了萤火虫的源代码,我发现了这个:

http://fbug.googlecode.com/svn/branches/firebug1.7/content/firebug/css.js

此代码仅适用于css部分。

const styleGroups =
{
    text: [
        "font-family",
        "font-size",
        "font-weight",
        "font-style",
        "color",
        "text-transform",
        "text-decoration",
        "letter-spacing",
        "word-spacing",
        "line-height",
        "text-align",
        "vertical-align",
        "direction",
        "column-count",
        "column-gap",
        "column-width"
    ],

    background: [
        "background-color",
        "background-image",
        "background-repeat",
        "background-position",
        "background-attachment",
        "opacity"
    ],

    box: [
        "width",
        "height",
        "top",
        "right",
        "bottom",
        "left",
        "margin-top",
        "margin-right",
        "margin-bottom",
        "margin-left",
        "padding-top",
        "padding-right",
        "padding-bottom",
        "padding-left",
        "border-top-width",
        "border-right-width",
        "border-bottom-width",
        "border-left-width",
        "border-top-color",
        "border-right-color",
        "border-bottom-color",
        "border-left-color",
        "border-top-style",
        "border-right-style",
        "border-bottom-style",
        "border-left-style",
        "-moz-border-top-radius",
        "-moz-border-right-radius",
        "-moz-border-bottom-radius",
        "-moz-border-left-radius",
        "outline-top-width",
        "outline-right-width",
        "outline-bottom-width",
        "outline-left-width",
        "outline-top-color",
        "outline-right-color",
        "outline-bottom-color",
        "outline-left-color",
        "outline-top-style",
        "outline-right-style",
        "outline-bottom-style",
        "outline-left-style"
    ],

    layout: [
        "position",
        "display",
        "visibility",
        "z-index",
        "overflow-x",  // http://www.w3.org/TR/2002/WD-css3-box-20021024/#overflow
        "overflow-y",
        "overflow-clip",
        "white-space",
        "clip",
        "float",
        "clear",
        "-moz-box-sizing"
    ],

    other: [
        "cursor",
        "list-style-image",
        "list-style-position",
        "list-style-type",
        "marker-offset",
        "user-focus",
        "user-select",
        "user-modify",
        "user-input"
    ]
};

获取所有样式的函数。

updateComputedView: function(element)
{
    var win = element.ownerDocument.defaultView;
    var style = win.getComputedStyle(element, "");

    var groups = [];

    for (var groupName in styleGroups)
    {
        var title = $STR("StyleGroup-" + groupName);
        var group = {title: title, props: []};
        groups.push(group);

        var props = styleGroups[groupName];
        for (var i = 0; i < props.length; ++i)
        {
            var propName = props[i];
            var propValue = stripUnits(rgbToHex(style.getPropertyValue(propName)));
            if (propValue)
                group.props.push({name: propName, value: propValue});
        }
    }

    var result = this.template.computedTag.replace({groups: groups}, this.panelNode);
    dispatch(this.fbListeners, 'onCSSRulesAdded', [this, result]);
}

function stripUnits(value)
{
    // remove units from '0px', '0em' etc. leave non-zero units in-tact.
    return value.replace(/(url\(.*?\)|[^0]\S*\s*)|0(%|em|ex|px|in|cm|mm|pt|pc)(\s|$)/gi, function(_, skip, remove, whitespace) {
    return skip || ('0' + whitespace);
    });
}

在这段代码中我想出了

win.getComputedStyle(element, "")

获取元素的所有样式,然后使用for循环获取所有样式并打印出来。所以我认为getComputedSTyle是要使用的主要功能,在此之后你可以逐个获取道具:

style.getPropertyValue(propName)

答案 5 :(得分:1)

根据kirilloid的回答,我为Chrome创建了一个开发人员工具扩展程序,其中包含用于捕获页面片段的样式和标记的代码。扩展程序位于Chrome Web Store,位于Github。所有“作者样式”输出选项都使用该方法迭代样式表。

enter image description here

答案 6 :(得分:0)

.css()方法获取元素的特定样式...我不知道您是否可以检索所有样式:

http://api.jquery.com/css/

答案 7 :(得分:0)

通常,您可以使用.attr('style')访问样式参数。如果要访问计算样式,可以在Opera,Firefox,Chrome和其他理想浏览器中使用window.getComputedStyle(element)。对于IE,你会对element.currentStyle做同样的事情。

此外,如果您希望访问单独的CSS样式,可以使用jQuery .css 方法。就像这样$(“#divId”)。css('font-size')。

答案 8 :(得分:0)

您可以在document.styleSheets下的样式标记内定义样式表。您可以将规则读入地图,然后通过selectorText查找它们。所以通过id:“#id”,按类:“。className”。通过safari或chrome,您可以使用getMatchedCSSRules