reactjs 将内容从div +样式复制到新窗口

3hvapo4f  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(87)

我尝试从div复制内容,创建新窗口并将内容放入其中。
代码是工作,但没有得到的样式。我怎么能复制所有的样式引用从源页面?
附言:我用的是bootstrap + react

function PrintElem() {

    var nWindow = window.open('', 'PRINT', 'height=400,width=600');
    let content = document.getElementById('printablediv').innerHTML;
    content.print();
    nWindow.document.write('<html><head><title>' + document.title + '</title>');
    nWindow.document.write('</head><body >');
    nWindow.document.write(content);
    nWindow.document.write('</body></html>');

    nWindow.document.close();
    nWindow.focus();

    nWindow.print();
}
oyt4ldly

oyt4ldly1#

我发现了如何:你需要复制头属性,这是css引用的地方。

export const PrintElement = (item) => {

    var nWindow = window.open('', 'PRINT', 'height=400,width=600');
    let element = document.getElementById(item);
    let header = document.getElementsByTagName('head');
    nWindow.document.write('<html>');
    nWindow.document.write('<header>');
    for (let headItem of header) {
        nWindow.document.write(headItem.outerHTML);
    }
    nWindow.document.write('</header>');
    nWindow.document.write('<body >');
    nWindow.document.write(element.outerHTML);
    nWindow.document.write('</body></html>');

    nWindow.document.close();
    nWindow.focus();

    nWindow.print();
}

相关问题