【问题标题】:How to retrieve both html and styles of a page section?如何检索页面部分的 html 和样式?
【发布时间】:2012-11-06 19:59:59
【问题描述】:

我正在尝试检索网页部分(通常是 div 或 table 元素)的当前内容。目的是将其显示为独立的(例如用于打印目的)或将其插入另一个页面。对我来说,不仅要收集元素,还要收集它们的计算样式,因为某些内容已被其他脚本突出显示或颜色编码。

我可以使用innerHTML 获取html,并使用getComputedStyle 获取特定元素的样式。但是我如何获得整个部分的 html 和样式?

【问题讨论】:

    标签: javascript css innerhtml


    【解决方案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);
      });
    });
    

    【讨论】:

    • 有趣。我看到的问题是它只会检索样式属性,而不是脚本插入的样式。我想我可以稍微修改一下以使用计算样式。
    • 是的,它只在页面加载时检查。我试图制作一个单一的 Javascript 文件,它可以摆脱 CSS 中存在的所有跨浏览器问题。一些自动 CSS 编写器。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多