這個想法是在頁面上的某處設置iframe內容,並通過隱藏原始內容來僅打印該內容。
這可以通過在啓動Ctrl + P事件(通過JavaScript)時獲取iframe內容並僅打印其內容(通過CSS @media類型)來完成。
HTML代碼:
<div id="dummy_content"><!-- Here goes the iframe content, which will be printed --></div>
<div id="content_wrapper">
<div id="current_content">Current Content that the user see<div>
<iframe id="myIframe" src="iframe.html"></iframe>
</div>
CSS代碼:
@media screen {
#dummy_content {
display:none; /* hide dummy content when not printing */
}
}
@media print {
#dummy_content {
display:block; /* show dummy content when printing */
}
#content_wrapper {
display:none; /* hide original content when printing */
}
}
JavaScript代碼:
var dummyContent = document.getElementById("dummy_content");
function beforePrint() {
var iFrame = document.getElementById("myIframe");
dummyContent.innerHTML = iFrame.contentWindow.document.body.innerHTML; // populate the dummy content (printable) with the iframe content
}
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode == 80) {
beforePrint();
}
}
我一直在尋找一個JavaScript解決方案,因爲CSS不適合我。標記爲答案。 – Burjua
謝謝。對於它的價值,我完全同意xDNP應得賞金獎,並且我也提出了他們的答案。 – Julian