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

前端 未结 9 1947
不知归路
不知归路 2020-12-01 08:22

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 style

相关标签:
9条回答
  • 2020-12-01 08:38

    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 currentStyle property 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.

    function computedStyle(el) {
        return el.currentStyle || window.getComputedStyle(el, null);
    }
    
    alert(computedStyle(document.body).color);
    
    0 讨论(0)
  • 2020-12-01 08:41

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

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

    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");
    
    0 讨论(0)
  • 2020-12-01 08:43

    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

    <div style="border:1px solid red;" id="testDiv">cfwcvb</div>
    
    0 讨论(0)
  • 2020-12-01 08:44

    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.

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

    0 讨论(0)
  • 2020-12-01 08:48

    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.

    0 讨论(0)
  • 2020-12-01 08:50

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

    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>
    
    0 讨论(0)
提交回复
热议问题