【问题标题】:other option beside document.body.innerHTMLdocument.body.innerHTML 旁边的其他选项
【发布时间】:2022-02-11 17:33:14
【问题描述】:

这是我的代码

  const printDiv = () => {
    const printContents = document.getElementById('id').innerHTML;
    const originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;

    return false;
  };

我知道当我使用 innerHTML 时,我会在一个元素中为我提供 HTML 的字符串表示,所以我无法处理按钮或类似的东西。

实际上,我可以通过重新加载来处理它,但最好的方法是什么?有没有不重新加载的选项让我回到同一页面?

【问题讨论】:

  • 为什么不在新标签页中打开可打印内容?
  • @Amir-Mousavi 使用窗口打开?如何使用 getElementByiD 打开新窗口?因为我已经在那个 id 中设置了 pdf 的样式
  • CSS? @media print { /* hide all but #id */ } -> developer.mozilla.org/en-US/docs/Web/CSS/@media
  • @Andreas你知道吗,如何在js中实现?

标签: javascript html reactjs


【解决方案1】:
const printContents = document.getElementById('id')
const win = window.open();
win.document.title ="some title";
win.document.body.innerHTML = printContents.innerHTML;

/* if content contains images that needs loading*/
const images = win.document.getElementsByTagName('img');
/*wait for them to load*/

win.print();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多