簡體   English   中英

使用 css 樣式打印 div

[英]To print a div with the css style

我制作了一個腳本來打印一個 div,但是當我看到預覽時,它沒有使用添加的 CSS 來“格式化”頁面。

HTML部分:

<center>Do not print this</center>              
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
            <input type='button' value='Print' onClick='Print()' />

JS部分

function Print(){
     var corpo = document.getElementById('content').innerHTML;

     var a = window.open('','','width=640,height=480');
     a.document.open("text/html");
     a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
     a.document.write(corpo);
     a.document.write("</div></body></html>");
     a.document.close();
     a.print(); 
}

現場版: https : //codepen.io/Pop1111/pen/Vwabbzd

看起來它只在之后加載 css。

有小費嗎?

您的代碼將創建無效的 HTML

嘗試

 function Print() { var corpo = document.getElementById('content').innerHTML; const html = []; html.push('<html><head>'); // assuming the first stylesheet on the parent page - use a different selector if not // or use +location.protocol+'//'+location.host+'/style.css">' html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">'); html.push('</head><body onload="window.focus(); window.print()"><div>'); html.push(corpo); html.push('</div></body></html>'); console.log(html) /* this will not work in the snippet - uncomment on your server var a = window.open('', '', 'width=640,height=480'); a.document.open("text/html"); a.document.write(html.join("")); a.document.close(); */ }
 <html> <head> <link rel="stylesheet" href="test.css" /> </head> <body> <center>Do not print this</center> <div>Hi mom!</div> <center>Print this</center> <div id="content" class="print">Hi dad!</div> <input type='button' value='Print' onClick='Print()' /> </body> </html>

您的新文檔未保存,因此沒有您預期的路徑,因此 CSS 文件的相對引用未找到 CSS。

要使其按預期工作,您需要將 CSS 引用更改為絕對引用,或者首先添加代碼以保存新的 HTML 文件。

這只是您測試它的方式,還是您的生產版本也會像這樣? (新文件,未保存,然后打印)。

您始終可以將實際的 CSS 本身注入到新文檔的樣式標記之間的頭部,而不僅僅是對 CSS 文件的引用。 試試那個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM