gpt4 book ai didi

javascript - @Media 打印样式未应用

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:28 25 4
gpt4 key购买 nike

堆栈 Blitz :https://stackblitz.com/edit/angular-xvdy1q
我想打印特定的 div

<div id="forPrint" (click)="onPrint('23')">
<div id="printable">
<div class="box">

</div>
</div>
</div>

Javascript 代码:

onPrint(url) {
this.mode = 'print';
const mywindow = window.open('', 'PRINT', 'height=400,width=600');

mywindow.document.write(`<html><head><title>${document.title}</title>`);
mywindow.document.write('</head><body >');
mywindow.document.write(`<h1> www.${url}</h1>`);
mywindow.document.write(document.getElementById('forPrint').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/

mywindow.print();
mywindow.close();

return true;
}

斯泰尔斯:

@media print {
html,
body {
height: 100% !important;
width: 100%!important;
h1 {
color: #1c7430;
}
}
#printable {
display: flex!important;
justify-content: center!important;
align-items: center!important;
height: 100% !important;
width: 700px!important;
}
.box {
width: 100px!important;
height: 100px!important;
background: green!important;
}
}

但是打开打印对话框后,框没有显示。所以没有应用任何样式,例如 h1.box。问题是什么?提前致谢。

最佳答案

您需要以某种方式将 CSS 注入(inject)新页面。

这里我创建了一个style标签并直接添加了CSS。您也可以链接到样式表:

function onPrint(url) {
this.mode = 'print';
const mywindow = window.open('', 'PRINT', 'height=400,width=600');

const styles = `html,
body {
height: 100% !important;
width: 100%!important;
}
h1 {
color: #1c7430;
}
#printable {
display: flex!important;
justify-content: center!important;
align-items: center!important;
height: 100% !important;
width: 700px!important;
}
.box {
width: 100px!important;
height: 100px!important;
background: green!important;
}`

mywindow.document.write(`<html><head><title>${document.title}</title>`);
mywindow.document.write(`<style>${styles}</style>`)
mywindow.document.write('</head><body >');
mywindow.document.write(`<h1> www.${url}</h1>`);
mywindow.document.write(document.getElementById('forPrint').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/

mywindow.print();
mywindow.close();

return true;
}

JSFiddle Demo

关于javascript - @Media 打印样式未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51149015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com