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

Javascript jQuery-如何使用元素的HTML获取所有样式/css(在内部/外部文档中定义),javascript,jquery,css,styles,Javascript,Jquery,Css,Styles,我知道$(“#divId”).html()将为我提供innerHtml。我还需要它的样式(可以通过类的方式定义),可以是内联的style属性,也可以是单独的标记中的所有样式/类 可能吗 更新 如果html类似于cfwcvb,并且在外部样式表中定义了#testDiv的css类,该怎么办 更新2 很抱歉没有早些澄清这一点 如果这是我的HTML <div id="divId"> <span class="someClass">Some innerText</spa

我知道
$(“#divId”).html()
将为我提供innerHtml。我还需要它的样式(可以通过类的方式定义),可以是内联的
style
属性,也可以是单独的
标记中的所有样式/类

可能吗

更新
如果html类似于
cfwcvb
,并且在外部样式表中定义了
#testDiv
的css类,该怎么办

更新2
很抱歉没有早些澄清这一点

如果这是我的HTML

<div id="divId">
    <span class="someClass">Some innerText</span>
</div>
然后,当我尝试获取
$(“#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>
.css()方法获取元素的特定样式。。。我不知道您是否可以检索所有样式:


通常,您可以使用.attr('style')访问样式参数。如果您想访问计算样式,可以在Opera、Firefox、Chrome和其他sane浏览器中使用window.getComputedStyle(元素)。对于IE,您也可以对element.currentStyle执行相同的操作


如果您希望访问单个CSS样式,也可以使用jQuery.CSS方法。例如$(“#divId”).css('font-size')。

您可以在脚本中使用类似的内容:-

<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>

$(函数(){
var styleVal=$('#testDiv').attr('style');
console.warn(“styleVal>>>”+styleVal);
})
简单的html是这样的

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

您可以获得一个样式对象,该对象表示在大多数浏览器中使用的元素的计算样式以及IE中元素的属性。但是,在浏览器中,对于快捷方式属性返回的值(例如
background
)、颜色RGB值、长度,甚至
font-weight
(请参见)。仔细测试

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

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

如果你想保存一个元素的所有样式,我想这会像你想的那样复杂 首先,我的第一个ide是firebug css控制台。这显示了一个元素的所有样式,我想怎么做? 因此,我搜索了firebug的源代码,发现:

此代码仅适用于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);
    });
}
获取元素的所有样式,然后使用for循环获取所有样式并打印出来。因此,我认为getComputedSTyle是要使用的主要功能,在此之后,您可以使用以下工具逐个获取道具:

style.getPropertyValue(propName)

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

<!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>


Element.prototype.getStyles=函数(){
var数组={};
var styles=window.getComputedStyle(此为空);
对于(变量i=0;i”+样式[“高度”]+“\n”+“行外样式:宽度->”+样式[“宽度”])
警报(“HTML:+divId.innerHTML”);
//跨度元素也是如此
},假);
#迪维德{
明确:两者皆有;
填充:3倍;
边框:2个点#CCC;
字体大小:107%;
线高:130%;
宽度:660px;
}
.某个班级{
颜色:蓝色;
}
试验
一些内部文本
(不确定,您需要它-以防万一)

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

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;
}

您可以在下的样式标签中定义样式表。您可以将规则读入地图,然后通过选择或文本查找规则。所以按id:#id,按类:.className。您可以使用safari或chrome。

根据kirilloid的回答,我为chrome创建了一个开发者工具扩展,其中包含用于捕获页面片段样式和标记的代码。分机位于中,并且处于启用状态。所有“作者样式”输出选项都使用该方法来迭代样式表


我认为你的标题应该是“如何获得所有样式…”,这也是类似的:你能告诉我你为什么需要这个吗?也许有一种简单的方法可以做到这一点。因为我正在将一个元素的html从一个文档复制到另一个窗口的文档(iFrame)。其他浏览器支持控制台吗?无论如何,并非所有浏览器都支持+1控制台,但您可以使用它作为替代。如果有一个类被分配给它,并且该类是在不同的css文件中定义的,该怎么办?谢谢,但如果它不支持所有浏览器,那么它将不适用于我。Console只是知道ucan的值,可以将其存储在变量中,并在任何地方使用它…我已经更新了我的问题,以防之前不清楚。谢谢你的回答。我试过你的回答。我已经用我尝试的结果更新了我的问题。我对您的回答做了一个小小的更改,就是
$(选择器)。从
$(选择器)。outerHTML()
中获取(0)。outerHTML
,这样我就不需要了。有一个愚蠢的错误--我已经修复了它(并在我的帖子中编辑了代码)。但我还有另一个问题:安全。在大多数浏览器中,用户无法通过DOM(即我使用的方式)从浏览器访问CSS
style.getPropertyValue(propName)
<!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>
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");