1

Web ページ セクション (通常は div または table 要素) の現在のコンテンツを取得しようとしています。目的は、(印刷目的などで) スタンドアロンとして表示するか、別のページに挿入することです。一部のコンテンツは他のスクリプトによって強調表示または色分けされているため、要素だけでなく計算されたスタイルも収集することが不可欠です。

innerHTML で html を取得し、getComputedStyle で特定の要素のスタイルを取得できます。しかし、セクション全体の html とスタイルの両方を取得するにはどうすればよいでしょうか?

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 に答える