我有一个HTML页面,想要打印其中的一部分内容。我知道一个JavaScript函数可以用来打印整个页面。
onClick="javascript:window.print(); return false;
但是我怎么打印页面的一部分呢?
如果有人有想法,请与我分享。
您应该使用单独的CSS文件来为打印媒体进行样式设置。这样可以在打印页面时隐藏/显示页面的部分内容。
HTML:
<div class="dont-print-that">
blah
</div>
print this!
包含:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
print.css
.dont-print-that{display:none;}
可以使用JavaScript和iframes来实现:
在JSFiddle中尝试一下
You can see the code here, but it won't work due to what are probably security limitations in StackOverflow's renderer.
const printButton = document.getElementById('print-button');
printButton.addEventListener('click', event => {
// build the new HTML page
const content = document.getElementById('name-card').innerHTML;
const printHtml = `<html>
<head>
<meta charset="utf-8">
<title>Name Card</title>
</head>
<body>${content}</body>
</html>`;
// get the iframe
let iFrame = document.getElementById('print-iframe');
// set the iFrame contents and print
iFrame.contentDocument.body.innerHTML = printHtml;
iFrame.focus();
iFrame.contentWindow.print();
});
<h1>Print your name badge</h1>
<div id="name-card" class="card">
<p>Hello my name is</p>
<h2>Max Powers</h2>
</div>
<p>You will be required to wear your name badge at all times</p>
<a id="print-button" class="btn btn-primary">Print</a>
<iframe id="print-iframe" width="0" height="0"></iframe>
您可以使用JavaScript将CSS样式应用于media="print"
,以隐藏除所需打印内容以外的所有内容。
您还可以在另一个窗口或[隐藏的]<iframe>
中加载页面并进行打印。