You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带样式的Div内容复制到新窗口?(Bootstrap+React)

解决新窗口同步原页面样式的问题

要同步原页面的所有样式(包括Bootstrap和自定义样式),你需要把原页面的样式引用(<link>和<style>标签)都复制到新窗口的<head>中,具体修改如下:

修改后的代码

function PrintElem() {
    var nWindow = window.open('', 'PRINT', 'height=400,width=600');
    // 获取需要打印的内容
    let content = document.getElementById('printablediv').innerHTML;
    // 收集原页面所有样式资源:link(如Bootstrap)和style标签
    const styles = Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))
                        .map(el => el.outerHTML)
                        .join('');

    // 写入新窗口的HTML结构,包含样式和内容
    nWindow.document.write(`
        <html>
            <head>
                <title>${document.title}</title>
                ${styles}
            </head>
            <body>
                ${content}
            </body>
        </html>
    `);

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

关键说明

  • 收集样式:通过document.querySelectorAll获取所有样式表链接(Bootstrap的<link>标签)和内联样式<style>标签,把它们的HTML代码直接复制到新窗口的头部。
  • 修复错误:原代码中content.print()是无效的(字符串没有print方法),已删除这一行。
  • 模板字符串:使用ES6模板字符串让代码更易读,避免拼接字符串的繁琐。

这样新窗口就能完全继承原页面的所有样式,包括Bootstrap的样式和你自定义的React组件样式。

内容的提问来源于stack exchange,提问作者xaotix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:40:25