1

I am trying to retrieve the current content of a Web page section (usually a div or table element). The objective is to display it as standalone (for example for printing purposes) or insert it in another page. It is essential for me to collect not only the elements but also their computed styles, as some content has been highlighted or color coded by other scripts.

I can get the html with innerHTML, and get the style of a specific element with getComputedStyle. But how would I get both html and styles for a whole section?

4

2 回答 2

1

我曾经在 jQuery 中做了一些可以检索所有(不是特定部分)样式的东西;.css 文件、样式标签和特定页面的内部样式。我不知道如何处理它,但也许你可以以某种方式使用这个脚本。它并非在所有情况下都有效,有时它会有点错误,因为我没有对其进行足够的测试。也许 StackOverflow 上还有其他人可以继续使用这段代码。;)

var all_css = {stylesheets:[], inner_head_styles:[], body_styles:[]};

$(function(){
  $.ajaxSetup({ 
    async: true,
    crossDomain: true,
    dataType: "text",
    type: "GET"
  });

  var calls = [];
  /*every non-cross-domain .css file*/
  $("head link[rel='stylesheet']").each(function(a, stylesheet){
    if($(stylesheet).attr("href").match(/((ftp|http|https):\/\/)?/)[0] == ""){
      var css_source = $(stylesheet).attr("href");
      var css_call = $.ajax({
        url: css_source,
        success: function(data){
          all_css.stylesheets.push(data);
        },
        error: function(e, f){
          alert(e, f);
        }
      });

      calls.push(css_call);
    }
    else{
      console.log("CSS SOLVER: Cross domain CSS's aren't going to be loaded!");
    }
  });

  /*every head style*/
  $("style").each(function(b, style){
    all_css.inner_head_styles.push($(this).text());
  });

  /*every element in the body that has a style attribute*/
  $("body[style], body *[style]").each(function(c, style){
    var css_html_node = $(style).context.nodeName;
    var css_class = typeof($(style).attr("class")) != "undefined" ? "."+$(style).attr("class") : "";
    var css_id = typeof($(style).attr("id")) != "undefined" ? "#"+$(style).attr("id") : "";

    css_class = css_class.replace(/\s/g, ".");
    var css_string = css_html_node + css_id + css_class + "{" + $(style).attr("style") + "}";
    all_css.body_styles.push(css_string);
  });


  $.when.apply(null, calls).done(function(){
    console.log(all_css);
  });
});
于 2012-11-06T20:20:43.030 回答
0

您无法真正检索某个部分的样式,您必须获取元素上的样式。

您必须记住,您不再处理原始 CSS,而是每个元素的计算样式。

于 2012-11-06T20:15:39.113 回答