【问题标题】:How to copy all CSS style from one DOM to another?如何将所有 CSS 样式从一个 DOM 复制到另一个?
【发布时间】:2018-11-04 03:37:33
【问题描述】:

我使用这种方法从我的 web 应用程序中复制一个 DIV 以在新选项卡中打印:https://stackoverflow.com/a/40389924/1062933 [谢谢!]

  printForm(): void {
    let printContents: any = document.getElementById('formTerms').innerHTML;
    let w: any = window.open();
    w.document.write(printContents);
    w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
    w.document.close(); // necessary for IE >= 10
    w.focus(); // necessary for IE >= 10
  }

但生成的 HTML 未格式化,没有主选项卡中的 CSS。

有没有办法同时复制该 DIV 中使用的 CSS 样式?

我正在使用 Angular4 和 Teradata Covalent

【问题讨论】:

  • 我需要这个,即使我必须复制原始页面的所有 CSS 才能使其正常工作......
  • Ctrl+S 网页,完成。查找所有.css 文件。
  • CSS文件由angular生成。
  • 在每个构建中,它们都有不同的名称。那是卑鄙的人。

标签: javascript css angular


【解决方案1】:

如果您知道哪些&lt;style&gt; 标记用于设置div 的样式,则可以将这些内容复制到新窗口中的新样式标记中。但是,这不会直接包含 div 本身的样式。

白色更手动,getComputedStyle 函数可以给出元素的当前样式,然后您可以在新窗口中应用它。如果您要复制的 div 中有子代,则必须递归执行此操作或将常见样式解析为生成的样式表。

链接页面有例子,这里我复制一下:

// print one or all of the style properties on the element
function dumpComputedStyles(elem,prop) {

  var cs = window.getComputedStyle(elem,null);
  if (prop) {
    console.log(prop+" : "+cs.getPropertyValue(prop));
    return;
  }

  var len = cs.length;
  for (var i=0;i<len;i++) {

    var style = cs[i];
    console.log(style+" : "+cs.getPropertyValue(style));
  }

}

【讨论】:

    猜你喜欢
    • 2011-02-12
    • 2011-05-28
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多