如何在React中将样式表/样式动态添加到iframe窗口

时间:2018-10-07 23:33:30

标签: javascript css reactjs iframe printing

我有一个React组件,当触发onClick方法时,它使用DOM查询将div的内容附加到iframe。然后,在iframe上触发.print()函数。虽然我能够成功触发此过程,但我没有做任何事情成功地将样式表或样式属性有效地附加到新创建的打印窗口中。

我尝试在文档的头部附加指向“ ./App.css”样式表的链接。我还尝试过将样式附加到头部。在这两种情况下,样式都将附加到头部,但不会反映在iframe的.print()窗口中。

如何将样式成功添加到创建的iframe中,以将其永久保存在框架的.print()窗口中?我已经在StackOverflow上尝试了iframe的现有方法。

我要尝试的方法如下:

  printContent = () => {
    var content = document.getElementById("divcontents");
    var pri = document.getElementById("ifmcontentstoprint").contentWindow;
    var head = pri.document.head;
    var style = document.createElement("style");
    style.innerHTML = `@media print and (color) { -webkit-print-color-adjust: exact; } h1 { color: teal }`
    head.appendChild(style); 
    pri.document.open();
    pri.document.write(content.innerHTML);
    pri.document.close();
    pri.focus();
    pri.print();
  }

0 个答案:

没有答案