Javascript 打印不适用于 css 更改

标签 javascript jquery html css

我正在尝试使用 jQuery 中的以下代码打印 html 内容

function printTable() {
    var divToPrint = document.getElementById("tblTranscript");
    newWin = window.open("");
    newWin.document.write('<html><head><title>Page</title>');
    newWin.document.write('<link rel="stylesheet" href="bootstrap.css"/>');
    newWin.document.write('</head><body>');
    newWin.document.write(divToPrint.outerHTML);
    newWin.document.write('</body></html>');
    newWin.print();
    newWin.close();
}

$('#print').on('click', function() {
    printTable();
})

它在打印预览中显示了上表,但 css 更改未应用于表。我为 css href 路径尝试了不同的组合。我可以直接通过浏览器访问 css 文件,但不知何故它在打印时不显示。

最佳答案

window.printItn = function(myID) {
    'use strict';
    var printContent = document.getElementById(myID),
        windowUrl = 'about:blank',
        uniqueName = new Date(),
        windowName = 'Print' + uniqueName.getTime(),
        stylesheet = $('body').data('theme'),
        WinPrint;

    WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
    WinPrint.document.write('<' + 'html' + '><head><style type="text/css">@import "' + stylesheet + '";</style></head><' + 'body style="background:none !important"' + '>');
    WinPrint.document.write(printContent.innerHTML);
    WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
};

$(".print").on('click', function() {
    printItn('YOUR-ID');
    return false;
});

这对我有用

关于Javascript 打印不适用于 css 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39853637/

相关文章:

javascript - 吉他和弦自定义标签简单解析器

javascript - 使用端口转发运行容器时,无法从 node.js 代码获取 docker 容器的 IP 地址

javascript - 在 AJAX 成功响应中执行 Javascript 代码(在单独的文件中)?

javascript - 数组值中的 HTML 标记

javascript - 使用隐藏字段是不好的做法吗?

javascript - ajax 加载 gif 成功后未删除

javascript - jQuery animate() 不适用于 If-Else 语句

Javascript:如何获取表格中选定的复选框项目

javascript - 当 img 固定到达页脚时,jQuery 停止滚动

javascript - 在javascript中将html表转换为数组