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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4781410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:04:08  来源:igfitidea点击:

jQuery - How to get all styles/css (defined within internal/external document) with HTML of an element

javascriptjquerycssstyles

提问by IsmailS

I know that $("#divId").html()will give me innerHtml. I also need its styles (which might be defined by the means of classes) either in-line styleattribute or all the styles/classes within a separate <style>tag.

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

Is it possible?

是否可以?

UPDATE
What if html is like <div id="testDiv">cfwcvb</div>and a css class for #testDivis defined in external stylesheet?

更新
如果 html 就像<div id="testDiv">cfwcvb</div>并且#testDiv在外部样式表中定义了一个 css 类怎么办?

UPDATE 2
Sorry for not clarifying this earlier

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

If this is my HTML

如果这是我的 HTML

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

And styles are defined in separate style sheet or in head styles.

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

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

Then when I try to get inner html of $("#divId").html()or call any other custom function, I need something like below

然后,当我尝试获取内部 html$("#divId").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>

UPDATE 3 for Answer by kirilloid
I ran below code in Command Window of Chrome Debugger tools for thispage itself and this is what I see TypeError: Cannot read property 'rules' of undefined

更新 3 for Answer by kirilloid
我在页面本身的 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");

采纳答案by kirilloid

outerHTML(not sure, you need it — just in case)

externalHTML(不确定,你需要它——以防万一)

Limitations: CSSOMis used and stylesheets should be from the same origin.

限制:使用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;
}

usage:

用法:

getElementChildrenAndStyles("#divId");

回答by Caio

No jQuery and no IE support, that's all I can do:

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

回答by Tim Down

You can get hold of a style object representing the computed style for an element using window.getComputedStyle()in most browsers and the element's currentStyleproperty in IE. There are several browser differences, however, with values returned for shortcut properties (such as background), color RGB values, lengths and even font-weight(see this useful test page). Test carefully.

您可以获取一个样式对象,该对象表示window.getComputedStyle()大多数浏览器中使用的元素的计算样式以及currentStyleIE 中的元素属性。然而,浏览器有几个不同之处,快捷方式属性(例如background)、颜色 RGB 值、长度甚至font-weight(请参阅此有用的测试页)的返回值。仔细测试。

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

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

回答by Mahima

You can use something like this for script:-

您可以将这样的内容用于脚本:-

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

and simple html would be like this

和简单的 html 会是这样的

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

回答by Gergely Fehérvári

if you want to save all of the style of an element i think this will be more complicated as you think first of all my first ide was the firebug css console. this shows all fo the style of an element and i thought how? so i searched for the source code of the firebug and i found this:

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

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

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

this code working only on the css part.

此代码仅适用于 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"
    ]
};

the function which gets all of the styles.

获取所有样式的函数。

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

in this code i figured out that the

在这段代码中,我发现

win.getComputedStyle(element, "")

to get all of the styles of an element, and then with a for loop gets all of the style and prints out. so i think the getComputedSTyle is the main function to use, and after this you can get the props one by one with:

获取元素的所有样式,然后使用 for 循环获取所有样式并打印出来。所以我认为 getComputedSTyle 是主要使用的函数,之后你可以通过以下方式一一获取道具:

style.getPropertyValue(propName)

回答by ifugu

Based on kirilloid's answer, I've created a developer tools extension for Chrome that incorporates that code for capturing styles and markup for a page fragment. The extension is in the Chrome Web Storeand is on Github. All of the "Author Styles" output options use that method for iterating over the stylesheets.

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

enter image description here

在此处输入图片说明

回答by Víctor B.

The .css() method gets a particular style of the element... I don't know if you can retrieve all styles:

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

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

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

回答by MeanEYE

Generally you can access style parameter using .attr('style'). If you want to access computed style you can use window.getComputedStyle(element) in Opera, Firefox, Chrome and other sane browsers. For IE you'd do the same with element.currentStyle.

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

Also if you wish to access individual CSS style you can do so with jQuery .cssmethod. Like so $("#divId").css('font-size').

此外,如果您希望访问单个 CSS 样式,您可以使用 jQuery .css方法来实现。像这样 $("#divId").css('font-size')。

回答by inf3rno

You can get the stylesheet defined inside style tags under document.styleSheets. You can read the rules into a map, and find them by selectorText. So by id: "#id", by classes: ".className". By safari or chrome you can use getMatchedCSSRules.

你可以在风格标签内定义样式表document.styleSheets。您可以将规则读入地图,并通过 selectorText 找到它们。所以通过id:“#id”,通过类:“.className”。通过 safari 或 chrome,您可以使用getMatchedCSSRules