用于打印的CSS不应用于动态生成的HTML



我正在尝试打印一个来自服务器端的HTML。我现在面临的主要问题是css由于某种原因没有被应用。看看小提琴。我做错什么了吗?

附言:使用带边框的JS是为了打开同一选项卡中的打印窗口。以前我遇到过这样的麻烦,当打开新选项卡时,原始选项卡上的JS停止工作,直到我关闭了第二个带有打印内容的选项卡

https://jsfiddle.net/7L9onps1/

@media print {
body * {
visibility: hidden;
}
.test {
visibility: visible;
position: absolute;
left: 0;
top: 0;
background: red;
color: red;
-webkit-print-color-adjust: exact; 
}
}

JS:

document.querySelector("#print").addEventListener("click", function() {
var html = '<div class="test">Test</div>';
print(html);
});
function print(html) {
// https://www.sitepoint.com/5-jquery-print-page-options/
document.innerHTML = html;
$('<iframe>', {
name: 'myiframe',
class: 'printFrame'
}).appendTo('body').contents().find('body').append(html);
window.frames['myiframe'].focus();
window.frames['myiframe'].print();
setTimeout(() => { $(".printFrame").remove(); }, 1000);
}

我正在使用库来做到这一点:https://github.com/DoersGuild/jQuery.print

最新更新