我正在尝试打印一个来自服务器端的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);
}